线性表是在一种常见的数据结构,主要包括插入、删除、查找等功能。
主要代码如下:
#include <iostream> using namespace std; //定义基类 template <class T> class slistNode { public: slistNode(){next=NULL;} T data; slistNode *next; protected: private: }; //定义链表类 template <class T> class myList { public: myList(); unsigned int length(); void add(T x); void traversal(); bool isEmpty(); void sdelete (T x); void insert(T x,int i); void insertHead(T x); int find(T x); protected: private: unsigned int listlength;//链表长度 slistNode<T> *node;//临时用的节点 slistNode<T> *lastnode;// slistNode<T> *headnode;// }; template <class T> myList<T>::myList(){ listlength=0; node=NULL; lastnode=NULL; headnode=NULL; } //链表长度 template <class T> unsigned int myList<T>:: length(){ return listlength; } //在链表后添加一下数据 template <class T> void myList<T>:: add(T x){ node=new slistNode<T>(); node->data=x; if (NULL==lastnode) { headnode=node; lastnode=node; } else { lastnode->next=node; lastnode=node; } ++listlength; } //每次都是在头结点插入新值 template <class T> void myList<T>::insertHead(T x){ node=new slistNode<T>(); if (NULL==headnode) { node->data=x; headnode=node; headnode->next=NULL; lastnode=headnode; } else { node->data=x; node->next=headnode; headnode=node; } ++listlength; } //遍历 template <class T> void myList<T>::traversal(){ node=headnode; while(node!=NULL) { cout<<node->data<<endl; node=node->next; } cout<<endl; } //判断是否为空 template <class T> bool myList<T>::isEmpty(){ bool temp; if (0==listlength) temp=true; else temp=false; return temp; } //删除某一个值 先考虑头节点、再考虑尾节点、最后再考虑在中间的结果 template <class T> void myList<T>::sdelete (T x){ if (0!=listlength) { if (x==headnode->data) { node=headnode; headnode=node->next; delete node; if (headnode==lastnode) { headnode=lastnode=NULL; } --listlength; return; } node=headnode; while(node->next!=NULL&&node->next->data!=x) { node=node->next; } if (node->next==NULL) { return; } if (node->next=lastnode) { lastnode=node; delete(node->next); node->next=NULL; --listlength; } else { slistNode<T> *tem; tem=node->next; node->next=tem->next; delete(tem); tem->next=NULL; --listlength; } } } //在中间插值,排除插入头节点 template <class T> void myList<T>::insert(T x,int i){ if (i>listlength)return; if (0==i) { slistNode<T> *tem=new slistNode<T>(); tem->data=x; tem->next=headnode; headnode=tem; ++listlength; return; } node=headnode; for (int j=2;j<=i;j++) { node=node->next; } if (node->next==NULL) { slistNode<T> *tem=new slistNode<T>(); tem->data=x; tem->next=NULL; node->next=tem; lastnode=tem; ++listlength; return; } slistNode<T> *tem=new slistNode<T>(); tem->data=x; tem->next=node->next; node->next=tem; ++listlength; } //查找是否有这个数据 template <class T> int myList<T>::find(T x){ if (listlength==0) return -1; node=headnode; while(node->next!=NULL&&node->data!=x) node=node->next; if (node->next==NULL) { if (node->data==x) { return 1; } else return 0; } return 1; }