文档详情

链表的类实现.doc

发布:2018-02-07约3.29千字共5页下载文档
文本预览下载声明
捣腾了蛮久,终于把《数据结构与算法》中的类实现链表的算法弄明白了。 我个人就目前情况来看,非常的佩服本书的作者。虽然这本书翻译的时候源代码贴出了太多的错误, 但总不至于被它弄糊涂了。 尽管有错误,但是这本书详细的方法解说,以及作者缜密的思维方法,还有怎么样 避免不必要的bug都让我受益匪浅。不过在代码的具体实现的时候,还是困难重重,就 好比求链表的长度。我曾试着写了一个length函数返回其长度,但是等我用了 int length() { return head-tail; } 我才知道 ,我犯了很低级的错误。于是乎就屁颠屁颠跑到CSDN找了一顿批,最后没办法之后再IntSLList类里面 加上一个length标签。问题也就算是这样马马虎虎解决了吧。 在最后我还想提醒自己以及大家一句,别忘了把内存还给电脑。 以下是具体的实现代码。 #pragma once #includeiostream using namespace std; class IntNode { public: int info; IntNode *next; IntNode(int el,IntNode*ptr=0) { info=el; next=ptr; } }; class IntSLList { public: IntSLList() { head=tail=0; } ~IntSLList(); int isempty() { return head==0; } void addToHead(int); void addToTail(int); int deleteFromHead();//delete the head and return its value; int deleteFromTail();//delete the tail and return its value; int getLength(); void deleteNode(int); void printLink() const; bool isInList(int) const; void InitLength(); private: IntNode *head,*tail; int length; }; IntSLList::~IntSLList() { for(IntNode*p;!isempty();) { p=head-next; delete head; head=p; } } void IntSLList::addToHead(int n) { head=new IntNode(n,head); if(tail==0)//this is the special circumstances; tail=head; length++; } void IntSLList::addToTail(int n) { if(tail!=0)//if list not empty { tail-next=new IntNode(n); tail=tail-next; } else head=tail=new IntNode(n); length++; } int IntSLList::deleteFromHead() { if(isempty()) throw(empty); int el=head-info; IntNode*temp=head; if(tail==head)//if only have one node in the list; tail=head=0; else { head=head-next; length--; } delete temp; return el; } int IntSLList::deleteFromTail() { int el=tail-info; if(head==tail)//if only have one node in the list; { delete head; head=tail=0; } else { IntNode*temp; for(temp=head;temp-next!=tail;temp=temp-next); delete tail; tail=temp; tail-next=0; length--; } return el; } void IntSLList::deleteNode(int n) { if(head!=0) if(head==tailn
显示全部
相似文档