下面是编程之家 jb51.cc 通过网络收集整理的代码片段。
编程之家小编现在分享给大家,也给大家做个参考。
#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///////////////////
以上是编程之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。
如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。