单链表的插入和删除 C++实现
发布时间:2020-12-16 07:42:46 所属栏目:百科 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 #pragma once ////定义链表和节点/////////////////////////////////////////// ////节点类 class Node { public: ////methods Node(void); Node(int
以下代码由PHP站长网 52php.cn收集自互联网 现在PHP站长网小编把它分享给大家,仅供参考 #pragma once ////定义链表和节点/////////////////////////////////////////// ////节点类 class Node { public: ////methods Node(void); Node(int data); ~Node(void); /////members Node* next; int data; }; ////链表类 class MyLinkTable{ public: //////methods void RemovdeAt(int position,Node* head); void Add(Node* node,Node* head); void AddAfter(int position,Node* head,Node* node); bool IsEmpty(Node* head); void PrintNodes(Node* head); /////members Node* head; }; ///////////////////////////////////////////////实现/////////////////// #include "StdAfx.h" #include "Node.h" #include <iostream> /////////node methods///////////// Node::Node(void) { Node::data=0; Node::next=NULL; } Node::Node(int data) { Node::data = data; Node::next=NULL; } Node::~Node(void) { } //////////////////////end////////////////// ///////////linkTable methods////////////// ////移除某个节点////////////////// void MyLinkTable::RemovdeAt(int position,Node* head){ if(this->IsEmpty(head) || position < 0){ return; } ////如果要删除头结点 if(position == 0) { Node* n = head; head=head->next; delete n; MyLinkTable::head = head; return; } Node* p = new Node; p=head; for(int i=0;i<position-1&&p!=NULL;p=p->next,i++); if(p!=NULL) { Node* n = p->next; p->next = p->next->next; free(n); } } /////在末尾追加节点 void MyLinkTable::Add(Node* node,Node* head){ if(this->IsEmpty(head)) { return; } Node* p = head; while(p->next) { p=p->next; } p->next = node; node->next = NULL; } /////在制定位置后面添加节点 void MyLinkTable::AddAfter(int position,Node* node){ if(this->IsEmpty(head)){ return; } Node* p = head; for(int i = 0;i < position && p->next != NULL;p=p->next,i ++); node->next = p->next; p->next = node; } ////判断链表是否非空 bool MyLinkTable::IsEmpty(Node* head){ return head==NULL; } ////打印链表 void MyLinkTable::PrintNodes(Node* head){ std::cout<<std::endl; while(head){ std::cout<<head->data<<" "; head=head->next; } } ///////////////end/////////////////// 以上内容由PHP站长网【52php.cn】收集整理供大家参考研究 如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |