码迷,mamicode.com
首页 > 其他好文 > 详细

双向链表的实现

时间:2016-04-18 00:58:44      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:

  由于一直对链表不太熟,所以今天晚上就趁着没什么事,写个双向链表玩玩。

 1 #include<iostream>
 2 using namespace std;
 3 struct Node
 4 {
 5     int Num=0;
 6     Node *Next=nullptr;
 7     Node *Pre=nullptr;
 8 };
 9 
10 int main()
11 {
12     Node *head, *current, *pre=nullptr;
13     int count = 2;
14     //为什么一开始就给head分配内存,而不是像单向链表那样由current将内存分配给head呢?
15     //原因是如果一开始没有给head分配内存,那么在实现双向链表最关键的一步----head->next=current,current=head,这一步上就会出错
16     //因为一开始head是没有分配内存给他的,所以将current的内存给了head,而current本身只能和head共享一块内存了,这样就不能实现双向性了
17 
18     head = new Node;
19     head->Num = count - 1;
20     while (count <= 10)
21     {
22         current = new Node;
23         if (head->Next == nullptr)
24         {
25             head->Next = current;
26             current->Pre = head;
27             current->Num = count;
28         }
29         else
30         {
31             pre->Next = current;
32             current->Pre = pre;
33             current->Num = count;
34         }
35         pre = current;
36         current = current->Next;
37         ++count;
38     }
39     //正序输出
40     current = head;
41     while (current->Next != nullptr)
42     {
43         cout << current->Num << " ";
44         current = current->Next;
45     }
46     cout << current->Num;
47     cout << endl;
48     //逆序输出
49     current = current;
50     while (current != nullptr)
51     {
52         cout << current->Num << " ";
53         current = current->Pre;
54     }
55 
56 
57 
58 
59 
60     system("pause");
61     return 0;
62 }

 

双向链表的实现

标签:

原文地址:http://www.cnblogs.com/nkuhjp/p/5402869.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!