链表

xiaoxiao2021-02-28  51

#include <iostream> using namespace std; template<class T> struct node {     T data[];     node<T> *next;// }; template<class T> class linklist { public:     linklist();               //建立只有头结点的空链表     linklist(T a[],int n);    //建立有n个元素的单链表     ~linklist();     int lengh();     T get(int i);        //按位置查找     int locate(T x);     //按值查找元素     void seek(int i,T x);   //i是位置(插入)     x是值     T Delete(int i);     void printlist(); private:     node<T> *first;      //单链表的头指针 } template <class T> linklist<T>::linklist() {     first=new node;      //生成头结点     first->next=NULL;    //头结点的指针域为空 } template <class T> linklist<T>::linklist(T a[],int n)      //建立有n个元素的单链表(头插法) {     first=new node;     first->next=NULL;    //初始化一个空链表     for(int i=0; i<n; i++)     {         s=new node;         s->data=a[i];         s->next=first->next;         first->next=s;     } } template <class T> linklist<T>::linklist(T a[],int n)      //wei {     first=new node;     r=first;     for(int i=0; i<n; i++)     {         s=new node;         s->data=a[i];         r->next=s;         r=s;     } } template <class T> void linklist<T>::printlist() {     p=first->next;//     while(p!=NULL)     {         cout<<p->data;         p=p->next;     } } template<class T> int linklist<T>::lengh() {     int c=0;     p=first->next;     while(p!=NULL)     {         p=p->next;//         c++;     }     return c; } template<class T> T linklist<T>::locate(T e) {     p=firt->next;     c=1;     while(p!=NULL)     {         if(e==p->data)             return c;         p=p->next;         cout++;     }     return 0; } template<class T> T linklist<T>::get(int i) {     p=firt->next;     c=1;     while(p!NULL&&c<i)//i=0     {         p=p->next;         cout++;     }     if(p==NULL)         throw "位置";     else         return p->data; } template<class T> void linklist<T>::insert(int i,T x) {     p=first->next;     int c=1;     while(p!=NULL&&c<i)     {         p=p->next;         c++;     }     if(p==NULL)         throw "位置";     else     {         s=new node;         s->data=x;         s->next=p->next;         p->next=s; //*******insert     } } template<class T> T linklist<T>::Delete(int i) {     p=first->next;     int c=0;     while(p!=NULL&&c<i-1)     {         p=p->next;         c++;     }     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> linklist<T>::~linklist() {     while(first!=NULL)     {         q=first;         first=first->next;         delete q;     } } int main() {     cout << "Hello world!" << endl;     return 0; }
转载请注明原文地址: https://www.6miu.com/read-2629143.html

最新回复(0)