c/c++:逆序建立链表

数据结构实验之链表三:链表的逆置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <iostream>
#include <cstring>
using namespace std;
struct node
{
int data;
struct node *next;
};


int main ()
{
std::ios::sync_with_stdio(false);

struct node *head, *tail, *p, *tmpNode;
head = new node;
head->next = NULL;
tail = head;

int num;

while(1)
{
p = new node;
p->next = NULL;
cin >> num ;
if(num == -1)
{
break;
}
p->data = num;
tail->next = p;
tail = p;
}

p = head->next;
head->next = NULL;

while(p->next != NULL)
{
tmpNode = p->next;
p->next = head->next;
head->next = p;
p = tmpNode;
}
p->next = head->next;
head->next = p;

p = head->next;
while(p->next != NULL)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<p->data<<endl;;

return 0;
}