标签:
由于一直对链表不太熟,所以今天晚上就趁着没什么事,写个双向链表玩玩。
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