【数据结构】链表反转
Time Limit: 1 s
Memory Limit: 128 MB
Submission:122
AC:59
Score:97.54
Description
链表是一种基础的数据结构, 他可以在常数时间内完成插入删除等操作。 HZNUOJ2141,2142,2145 等都是一些比较基础的链表实现。那么现在考虑这样一个问题,对于一个有头节点的单链表,如何完成其反转?
什么是反转:
如图所示为链表的反转操作。
那么现在请你完成: void ListReverse(List x) 函数, 他能够使带有头节点的链表 x 完成如上图的反转
主体代码:
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
#include <stdio.h>
#include <stdlib.h>
typedef int ElementType;
typedef struct Node *PtrToNode;
struct Node {
ElementType Data;
PtrToNode Next;
};
typedef struct Node Node;
typedef PtrToNode List;
List read()
{
List head = (List)malloc(sizeof(Node));
head->Next = NULL;
List now = head;
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
List tmp = (List)malloc(sizeof(Node));
tmp->Next = NULL;
scanf("%d", &tmp->Data);
now->Next = tmp;
now = now->Next;
}
return head;
}
void PrintList(List L)
{
int cot = 0;
List now = L->Next;
while (now)
{
if (cot)printf(" ");
cot++;
printf("%d", now->Data);
now = now->Next;
}
if (!cot)printf("NULL");
printf("\n");
}
void ListReverse(List x);
int main()
{
List L1 = read();
PrintList(L1);
ListReverse(L1);
PrintList(L1);
}
Samples
input
2
1 2
output
1 2
2 1