
classIntSLLNode{public:IntSLLNode(){//第一个构造函数初始化next指针为NULL next =0;}IntSLLNode(int i,IntSLLNode*in =0){//第二个构造函数设置两个成员数据的值 info = i; next = in;}int info;IntSLLNode*next;//指向下一个节点,这个节点的类型与本节点相同,这里要定义成公有成员,以便实施链表的操作};
classIntSLList{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 info;int deleteFromTail();// delete the tail and return its info;void deleteNode(int);bool isInList(int)const;void printAll()const;private:IntSLLNode*head,*tail;//两个私有成员变量,分别是指向单链表的头和尾的指针};
voidIntSLList::addToHead(int el){ head =newIntSLLNode(el,head);//一句话就完成了四步,这就是C++的魅力了if(tail ==0) tail = head;}
voidIntSLList::addToTail(int el){if(tail !=0){// 先判断链表是否为空 tail->next =newIntSLLNode(el); tail = tail->next;}else head = tail =newIntSLLNode(el);}
intIntSLList::deleteFromHead(){if(!isEmpty())//检查链表链表是否为空{int el = head->info;IntSLLNode*tmp = head;if(head == tail)//加入链表只有一个节点; head = tail =0;else head = head->next;delete tmp;return el;}else //std::cout<<"The List is Empty!"}
intIntSLList::deleteFromTail(){int el = tail->info;if(head == tail){// if only one node on the list;delete head; head = tail =0;}else{// if more than one node in the list,IntSLLNode*tmp;// find the predecessor of tail;for(tmp = head; tmp->next != tail; tmp = tmp->next);delete tail; tail = tmp;// the predecessor of tail becomes tail; tail->next =0;}return el;}
voidIntSLList::deleteNode(int el){if(head !=0) // if non-empty list;if(head == tail && el == head->info){// if only onedelete head;// node on the list; head = tail =0;}elseif(el == head->info){// if more than one node on the listIntSLLNode*tmp = head; head = head->next;delete tmp;// and old head is deleted;}else{// if more than one node in the listIntSLLNode*pred,*tmp;for(pred = head, tmp = head->next;// and a non-head node tmp !=0&&!(tmp->info == el);// is deleted; pred = pred->next, tmp = tmp->next)if(tmp !=0){ pred->next = tmp->next;if(tmp == tail) tail = pred;delete tmp;} }}}boolIntSLList::isInList(int el)const{IntSLLNode*tmp;for(tmp = head; tmp !=0&&!(tmp->info == el); tmp = tmp->next);return tmp !=0;}原文:http://www.cnblogs.com/star91/p/4761742.html