基于链表的列表实现

来源:互联网 发布:地坪找平层算法 编辑:程序博客网 时间:2024/06/08 17:42
//-------------LinkedList.h--------------  #include<iostream>  #ifndef LIST#define LISTtypedef int ElementType;class List{private:class Node{public:ElementType data;Node *next;Node(ElementType value,Node *link=0):data(value),next(link){}};typedef Node * NodePointer;public:List();~List();List(const List & original);const List & operator=(const List & rightHandSide);bool empty() const;void insert(ElementType item,int pos);void erase(int pos);void display(ostream & out) const;private:    NodePointer first;int mySize;};ostream & operator<<(ostream & out,const List & aList);#endif

//--------------LinkedList.cpp----------------   #include<cassert>using namespace std;    #include"LinkedList.h"  List::List()  :first(0),mySize(0)  {}    List::~List()  {      NodePointer currPtr=first,                  nextPtr;while(currPtr!=0){nextPtr=currPtr->next;delete currPtr;currPtr=nextPtr;}mySize=0;}    List::List(const List & original)  {  first=0;mySize=0;if(!original.empty()){first=new Node(original.first->data);NodePointer origPtr=original.first->next;mySize=original.mySize;while(origPtr!=0){first->next=new Node(origPtr->data);first=first->next;origPtr=origPtr->next;}}}    const List & List::operator=(const List & rightHandSide)  {      if(this!=&rightHandSide)      {this->~List();        if(rightHandSide.empty())                first=0;else{first=new Node(rightHandSide.first->data);NodePointer ptr=first;NodePointer rhsPtr=rightHandSide.first->next;mySize=rightHandSide.mySize;while(rhsPtr!=0){ptr=new List::Node(rhsPtr->data);ptr=ptr->next;rhsPtr=rhsPtr->next;}}             }      return *this;  }    bool List::empty() const  {      return first==0;  }    void List::display(ostream & out) const  {  NodePointer ptr;    for(ptr=first;ptr!=0;ptr=ptr->next)out<<ptr->data;out<<endl;}    ostream & operator<<(ostream & out,const List & aList)  {      aList.display(out);      return out;  }    void List::insert(ElementType item,int pos)//插入到第pos个节点之后的位置{assert(pos>0||pos==0);NodePointer ptr=first,            newptr=new Node(item);if(pos==0){newptr->next=first;          first=newptr;}else if(pos<mySize||pos==mySize){for(int i=1;i<pos;i++)    ptr=ptr->next;        newptr->next=ptr->next;    ptr->next=newptr;}else{cerr<<"***The position out of range***";exit(1);}    mySize++;  }    void List::erase(int pos) //删除第pos个节点{    assert((pos>0)&&(pos<mySize||pos==mySize));NodePointer ptr=first,        predptr;if(pos==1)      first=ptr->next;else{pos=pos-2;while(pos>0){ptr=ptr->next;pos--;}predptr=ptr; //ptr是删除节点前一个节点的指针ptr=ptr->next; //ptr是将要删除的节点predptr->next=ptr->next;}delete ptr;mySize--;       }  

//-------------LinkedList_main.cpp-----------------  #include<iostream>  using namespace std;    #include"LinkedList.h"    int main()  {       List aList;    /*     //     //                             */  system("pause");     return 0;  } 

原创粉丝点击