双向链表的实现

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

 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 }

 

转载于:https://www.cnblogs.com/nkuhjp/p/5402869.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值