链表的就地逆置(其实只是练练链表)

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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <iostream>
using namespace std;

struct Node {
int data;
Node *next;
};

//函数声明
//将元素插入有序单链表中,插入后仍然有序
void Insert (Node *la, int x);
//销毁单链表
void Destory (Node *la);
//打印单链表
void Print (Node *la);
//单链表就地逆置
void Reverse (Node *la);

int main ()
{
//建立带头节点的单链表
Node *la = new Node;
la->next = NULL;

int n;
cin >> n;

for (int i = 0; i < n; i++) {
int x;
cin >> x;
//将元素插入有序单链表中,插入后仍然有序
Insert (la, x);
}
//打印单链表
Print (la);
//单链表就地逆置
Reverse (la);
//打印单链表
Print (la);
//销毁单链表
Destory (la);

return 0;
}

//将元素插入有序单链表中,插入后仍然有序
void Insert (Node *la, int x)
{
//申请结点
Node *q= new Node;
q->data = x;
//查找合适插入位置
Node *p = la;
while (p->next && x > p->next ->data)
p = p->next; //往后移一位置
//将结点插入p所指结点后
q->next = p ->next ;
p->next = q;
}

//销毁单链表
void Destory (Node *la)
{
while (la) {
Node *q = la->next;
delete la;
la = q;
}
}

//打印单链表
void Print (Node *la)
{
//头结点无数据
la = la ->next;
if (la) {//数据比-〉多一个
cout<<la->data;
la = la->next;
}
while (la) {
cout <<"->" <<la->data;
la = la->next;
}
cout << endl;
}
//单链表就地逆置
void Reverse (Node *la)
{
//将原带头结点单链表截成两段
Node *p= la->next;
la->next = NULL;
//将P所指单链表(无头结点)依次摘下插入La所指单链表首,完成就地逆置
while (p) {
Node *q = p->next;
p->next = la->next;
la->next = p;
p = q;
}
}