代码改变世界

带头结点的单链表反转

2011-08-22 14:33  Daniel Zheng  阅读(506)  评论(0编辑  收藏  举报
 1 #include <iostream>
2 using namespace std;
3
4 struct Node
5 {
6 public:
7 int data;
8 Node * pNode;
9 };
10
11
12 void CreateList(Node * Header)
13 {
14 cout<<"Input the node data and end by 0"<<endl;
15 int input;
16 int count = 0;
17 Node * oHeader = Header;
18 while(cin>>input)
19 {
20 if(input == 0)
21 break;
22 else
23 {
24 Node * T = new Node;
25 T->data = input;
26 T->pNode = NULL;
27 Header->pNode = T;
28 Header = Header->pNode;
29 ++count;
30 }
31 }
32 oHeader->data = count;
33 cout<<"Create "<<oHeader->data<<" Nodes"<<endl;
34 }
35
36 void PrintList(Node * Header)
37 {
38 while(Header->pNode != NULL)
39 {
40 Header = Header->pNode;
41 cout<<Header->data<<" ";
42 }
43 cout<<endl;
44 }
45
46 void ReversePrintList(Node * Header)
47 {
48 if(Header->pNode != NULL)
49 ReversePrintList(Header->pNode);
50 cout<<Header->data<<" ";
51 }
52
53
54 Node * ReverseList(Node * Header)
55 {
56 Node * pPre = NULL;
57 Node * pCurr = Header->pNode;
58 Node * pNext = pCurr->pNode;
59 while(pNext != NULL)
60 {
61 pCurr->pNode = pPre;
62 pPre = pCurr;
63 pCurr = pNext;
64 pNext = pNext->pNode;
65 }
66 pCurr->pNode = pPre;
67 Header->pNode = pCurr;
68
69 }
70 int main()
71 {
72 Node * Header = new Node;
73 CreateList(Header);
74 cout<<"Print sequence:"<<endl;
75 PrintList(Header);
76 cout<<"Print sequence by reverse:"<<endl;
77 ReversePrintList(Header->pNode);
78 cout<<endl<<"Reverse sequence and print:"<<endl;
79 Header->pNode = ReverseList(Header);
80 PrintList(Header);
81 cout<<"Number of Node is "<<Header->data<<endl;
82 return 0;
83 }