标签:tmp head int 单向 next 链表 IntSSLNode tail
链表节点(其中info 表示节点信息,next是下一个节点引用,其中info可以通过template<class T> 实现泛型链表)
#pragma once class IntSSLNode { public: IntSSLNode() { next = 0; info = 0; } IntSSLNode(int info, IntSSLNode* in = 0) { this->info = info; next = in; } int info; IntSSLNode* next; };
链表类
#pragma once #include "IntSSLNode.h" class IntSSList { public: IntSSList() { head = tail = 0; } ~IntSSList(); int isEmpty() { return head == 0; } void addToHead(int); void addTotail(int); int deleteFromHead(); int deleteFromTail(); void deleteNode(int); bool isInList(int) const; private: IntSSLNode* head, * tail; };
#include<iostream> #include "IntSSList.h" IntSSList::~IntSSList() { for (IntSSLNode* p; !isEmpty();) { p = head->next; delete head; head = p; } } void IntSSList::addToHead(int el) { head = new IntSSLNode(el, head); if (tail == 0) { tail = head; } } void IntSSList::addTotail(int el) { if (tail != 0) { tail->next = new IntSSLNode(el); tail = tail->next; } else { head = tail = new IntSSLNode(el); } } int IntSSList::deleteFromHead() { int el = head->info; IntSSLNode* temp = head; if (head == tail) { head = tail = 0; } else { head = head->next; } delete temp; return el; } int IntSSList::deleteFromTail() { int el = tail->info; if (head == tail) { delete head; head = tail = 0; } else { IntSSLNode* tmp; for (tmp = head; tmp->next != tail; tmp = tmp->next); delete tail; tail = tmp; tail->next = 0; } return el; } void IntSSList::deleteNode(int el) { if (head != 0) if (head == tail && el == head->info) { delete head; head = tail = 0; } else if (el == head->info) { IntSSLNode* tmp = head; head = head->next; delete tmp; } else { IntSSLNode* pred,* tmp; for (pred=head,tmp=head->next; tmp!=0 && !(tmp->info == el); pred=pred->next,tmp=tmp->next); if (tmp != 0) { pred->next=tmp->next; //三个节点删除中间一个节点,需要把上一个节点和下一个节点链接起来。 if (tmp == tail) //当删除的节点是末端节点则新的末端节点是上一个节点 { tail = pred; } delete tmp; } } } bool IntSSList::isInList(int el) const{ IntSSLNode* tmp; for (tmp = head; tmp != 0 && !(tmp->info == el); tmp = tmp->next); return tmp != 0; }
测试
int main() { IntSSList* list = new IntSSList(); list->addTotail(1); list->addTotail(2); list->addTotail(3); list->addTotail(4); list->addToHead(5); //int i = list->deleteFromHead(); //i = list->deleteFromTail(); list->deleteNode(3); }
标签:tmp,head,int,单向,next,链表,IntSSLNode,tail 来源: https://www.cnblogs.com/ms_senda/p/11312093.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。