自己创建链表类,实现几个基本操作

  1 /////List 创建 添加 删除
  2 #include <iostream>
  3 #include <string>
  4 #include <stack>
  5 using namespace std;
  6 class Node
  7 {
  8 public:
  9 int Data;
 10 Node*Node_next;
 11 Node():Data(0),Node_next(NULL){}
 12 };
 13 
 14 class list
 15 {
 16 Node*head;
 17 public:
 18 list(){head=NULL;}
 19 void insertlist(int iData);//链表尾部插入
 20 void Deletelist(int aDate);//链表结点的删除
 21 void Outputlist();//链表结点的输出
 22 void ReverseOutput();////反向输出
 23 Node*Gethead(){return head;}
 24 };
 25 void list::ReverseOutput()
 26 {
 27 stack<int> stk;
 28 Node* phd = head;
 29 while (phd!= NULL)
 30 {
 31 stk.push(phd->Data);
 32 phd = phd->Node_next;
 33 }
 34 while (!stk.empty())
 35 {
 36 cout<<stk.top()<<" ";
 37 stk.pop();
 38 }
 39 cout<<endl;
 40 
 41 }
 42 void list::Deletelist(int iData)
 43 {
 44 if (head != NULL)
 45 {
 46 Node* ptemp = head;
 47 if (head->Data == iData)
 48 {
 49 ptemp = head;
 50 head = head->Node_next;
 51 delete ptemp;
 52 }
 53 else
 54 {
 55 Node* pn = ptemp;
 56 while ((ptemp!= NULL) && (ptemp->Data != iData))
 57 {
 58 pn = ptemp;
 59 ptemp = ptemp->Node_next;
 60 }
 61 if (ptemp->Data == iData)
 62 {
 63 pn->Node_next = ptemp->Node_next;
 64 delete ptemp;
 65 }
 66 }
 67 }
 68 }
 69 void list::insertlist(int iData)
 70 {
 71 Node* pNewNode = new Node();
 72 pNewNode->Data = iData;
 73 if (head == NULL)
 74 {
 75 head = pNewNode;
 76 }
 77 else
 78 {
 79 Node* phd = head;
 80 Node* ptmp = head;
 81 while(phd != NULL)
 82 {
 83 ptmp = phd;
 84 phd = phd->Node_next;
 85 }
 86 ptmp->Node_next = pNewNode;
 87 }
 88 }
 89 
 90 void list::Outputlist()
 91 {
 92 Node* phd = head;
 93 while (phd!= NULL)
 94 {
 95 cout<<phd->Data<<" ";
 96 phd = phd->Node_next;
 97 }
 98 cout<<endl;
 99 }
100 
101 ////代码测试
102 #define LEN 10
103 int main()
104 {
105 list A;
106 int Data[10]={25,41,16,98,5,67,9,55,1,121};
107 for (int i=0; i<LEN; i++)
108 {
109 A.insertlist(Data[i]); //建立链表
110 }
111 
112 cout<<"
链表A:"<<endl;
113 A.Outputlist();
114 A.Deletelist(Data[5]);
115 cout<<"删除元素Data[5]后"<<endl;
116 A.Outputlist();
117 cout<<"删除元素Data[5]后反向输出"<<endl;
118 A.ReverseOutput();
119 return 0;
120 }
View Code
博客内容只为本人学习所感转载亦或自写,不足或错误之处请大家不吝赐教
原文地址:https://www.cnblogs.com/niupan369/p/4498723.html