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 }
链表是非常重要的 我们经常会用到,所以熟练的掌握有助实现!
链表使用的自我理解概念:
链表在物理地址逻辑相邻物理不相邻,有单链表,循环链表,双向链表,实现起来大同小异,主要是熟练掌握指针的使用。链表的节点数据部分可以是变量,数组,结构体,容器等。