c++数据结构 单链表的实现

来源:互联网 发布:网络借贷平台监管办法 编辑:程序博客网 时间:2024/06/05 18:47

linklist.h

#ifndef linklist_h#define linklist_htemplate<class t>struct node{    t data;    node<t>*next;};template<class t>class linklist{public:    linklist();    linklist(t a[], int n);    ~linklist();    int locate(t x);    void insert(int i, t x);    t del(int i);    void printlist();private:    node<t>*first;};#endif

linklist.cpp

#include<iostream>using namespace std;#include"linklist.h"template<class t>linklist<t>::linklist(){    first = new node<t>;    first->next = NULL;}template<class t>linklist<t>::linklist(t a[], int n){    node<t>*r, *s;    first = new node<t>;    r = first;    for (int i = 0; i < n; i++)    {        s = new node<t>;        s->data = a[i];        r->next = s; r = s;    }    r->next = NULL;}template<class t>linklist<t>::~linklist()//释放所有结点包括头结点{    node<t>*q = NULL;    while (first != NULL)    {        q = first;        first = first->next;        delete q;    }}template<class t>void linklist<t>::insert(int i, t x){    node<t>*p = first, *s = NULL;    int count = 0;    while (p != NULL&&count < i - 1)    {        p = p->next;        count++;    }    if (p == NULL)throw"位置";    else    {        s = new node<t>; s->data = x;        s->next = p->next; p->next = s;    }}template<class t>t linklist<t>::del(int i){    node<t>*p = first, *q = NULL;    t x;    int count = 0;    while (p != NULL&&count < i - 1)    {        p = p->next;        count++;    }    if (p == NULL||p->next==NULL)throw"位置";    else    {        q = p->next;        x = q->data;        p->next = q->next;        delete q;        return x;    }}template<class t>int linklist<t>::locate(t x){    node<t>*p = first->next;    int count = 1;    while (p != NULL)    {        if (p->data == x)return count;        p = p->next;        count++;    }    return 0;}template<class t>void linklist<t>::printlist(){    node<t>*p = first->next;    while (p != NULL)    {        cout <<p->data<< " ";        p = p->next;    }    cout << endl;}

linklist_main.cpp

#include<iostream>using namespace std;#include"linklist.cpp"int main(){    int r[5] = { 1, 2, 3, 4, 5 };    linklist<int>l(r, 5);    cout << "插入前数据为"<< endl;    l.printlist();    l.insert(2, 3);    cout << "插入后数据为" << endl;    l.printlist();    cout << "位置为5的元素位置为"<< endl;    cout << l.locate(5) << endl;    cout << "删除前数据为"<< endl;    l.printlist();    l.del(1);    cout << "删除后数据为"<< endl;    l.printlist();    return 0;}
0 0
原创粉丝点击