数据结构之单链表(C++)

来源:互联网 发布:企业软件管理系统 编辑:程序博客网 时间:2024/06/04 18:12
#ifndef LIST_H#define LIST_H/************************************************************************//* C++实现单链表                                                         /************************************************************************/#include <iostream>using namespace std;//这里为什么会出现NULL没有定义?typedef char Elemplent;//结点类定义class Node{public:Node* next;Elemplent data;Node();Node(Node* temptr = NULL,Elemplent temdata=' ');};//结点默认构造函数Node::Node(){next = NULL;}//创建新节点的构造函数Node::Node(Node* temptr,Elemplent temdata){next = temptr;data = temdata;}//链表类定义class List{protected:Node* head ;Node* temp;public:void init();List();~List();public:bool insertHeader(const Elemplent& elempent = ' ');bool insertTail(const Elemplent& elempent = ' ');int GetCount();Node* locateWithLocation(int position = 1) const;Node* locateWithElemplent(const Elemplent& elempent = ' ')const;bool Insert(const int position = 1,const Elemplent& elempent = ' ');bool Delete(const int position = 1);bool Clear();};//构造函数List::List(){init();}//析构函数及释放工作List::~List(){Clear();delete head;}void List::init(){head = new Node();temp =head;}//得到结点数int List::GetCount(){int i =0;while(temp->next!=NULL)i++;return i;}//在头插入元素bool List::insertHeader(const Elemplent& elempent /* = "" */){Node* newnode = new Node(head->next,elempent);head->next = newnode;return true;//存在bug}//在末尾插入元素bool List::insertTail(const Elemplent& elempent /* = ' ' */){Node* temp = locateWithLocation(GetCount());Node* newnode = new Node(NULL,elempent);temp->next = newnode;return true;}//得到指针用positionNode* List::locateWithLocation(int position /* = 1 */)const{int j=1;Node* temp;while(temp!=NULL&&j<position){j++;temp = temp->next;}return temp;}//得到指针用elemplentNode* List::locateWithElemplent(const Elemplent& elempent /* = ' ' */)const{Node* temp;while(temp!=NULL && elempent == temp->data){temp = temp->next;}return temp;}//在一个位置插入一个元素bool List::Insert(const int position /* = 1 */,const Elemplent& elempent /* = ' ' */){Node* temp = locateWithLocation(position);if(temp ==NULL){return false;}Node* newnode =new Node(temp->next,elempent);temp->next = newnode;return true;}//删除一个元素用位置;bool List::Delete(const int position /* = 1 */){Node* temp = locateWithLocation(position-1);if (temp ==NULL||temp->next==NULL){return false;}Node* delatenode  = temp->next;temp->next =delatenode->next;delete delatenode;return true;}//删除所有元素bool List::Clear(){while (GetCount()==0){Delete(1);}}#endif

原创粉丝点击