c/c++链表的实现

1 #include<iostream>
  2 #include<string>
  3 #define SIZE 3
  4 using std::cout;
  5 using std::endl;
  6 using std::string;
  7 
  8 
  9 class MyClass{
 10 public:
 11     struct DataInfo{
 12         int age;
 13         string name;
 14     };
 15 private:
 16     struct Queue{
 17         DataInfo  dataInfo;
 18         Queue *front;
 19         Queue *next;
 20     };
 21 private: 22     Queue  *head, *tail;
 23 
 24 public:
 25     inline Queue* CreateNode()
 26     {
 27         Queue *node;
 28         node = new Queue;
 29         return node;
 30     }
 31     inline void InsertNode(DataInfo dataInfo)//采用头插法
 32     {
 33         Queue *pNode;
 34         pNode = CreateNode();
 35         pNode->dataInfo = dataInfo;    
 36         pNode->next = head->next;
 37         head->next->front = pNode;
 38         head->next = pNode;
 39         pNode->front = head;
 40     }
 41     inline void DeleteNode()//采用头删法
 42     {
 43         Queue *pNode;
 44         pNode = head->next;
 45         head->next = pNode->next;
 46         pNode->next->front = head;
 47 
 48     }
 49     inline void InitinalQueue()
 50     {
 51         head = CreateNode();
 52         tail = CreateNode();
 53         head->next = tail;
 54         head->front = NULL;
 55         tail->front = head;
 56         tail->next = NULL;
 57     }
 58     inline void OutputQueue()
 59     {
 60         Queue *pNode;
 61         pNode = head->next;
 62         do{
 63             cout << pNode->dataInfo.age <<" "<< pNode->dataInfo.name << endl;
 64             pNode = pNode->next;
 65         } while (pNode!=tail);
 66     }
 67     inline void  FreeSpace()//释放空间
 68     {
 69         Queue *pNode;
 70         pNode = head->next;
 71         while (pNode != NULL)
 72         {
 73             delete pNode->front;
 74             pNode = pNode->next;
 75         }
 76         delete tail;
 77     }
 78 };
 79 void  main()
 80 {
 81     MyClass myClass;
 82     myClass.InitinalQueue();
 83     MyClass::DataInfo  dataInfo[SIZE];
 84     dataInfo[0].age = 21;
 85     dataInfo[0].name = "436酱油哥";
 86 
 87     dataInfo[1].age = 22;
 88     dataInfo[1].name = "436酱油哥";
 89 
 90     dataInfo[2].age = 23;
 91     dataInfo[2].name = "436酱油哥";
 92 
 93     myClass.InsertNode(dataInfo[0]);
 94     myClass.InsertNode(dataInfo[1]);
 95     myClass.InsertNode(dataInfo[2]);
 96 
 97     myClass.OutputQueue();
 98     myClass.FreeSpace();//释放new 占用的空间
 99     
100     system("pause");
101 }

链表是非常重要的 我们经常会用到,所以熟练的掌握有助实现!

链表使用的自我理解概念:

链表在物理地址逻辑相邻物理不相邻,有单链表,循环链表,双向链表,实现起来大同小异,主要是熟练掌握指针的使用。链表的节点数据部分可以是变量,数组,结构体,容器等。

原文链接: https://www.cnblogs.com/spring-hailong/p/6183818.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/245844

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月14日 上午1:07
下一篇 2023年2月14日 上午1:07

相关推荐