-
Notifications
You must be signed in to change notification settings - Fork 0
/
reverseList.c
84 lines (73 loc) · 1.57 KB
/
reverseList.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
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct ListNode
{
int key;
struct ListNode* next;
} ListNode;
ListNode* reverseList(ListNode *pHead);
int main()
{
int num;
ListNode *list = NULL;
ListNode *pNode;
ListNode *tail;
while(scanf("%d", &num) != EOF){
// input list
while(num--){
if(list == NULL){
list = (ListNode*) malloc(sizeof(ListNode));
tail = list;
scanf("%d", &tail->key);
tail->next = NULL;
}
else{
tail->next = (ListNode*) malloc(sizeof(ListNode));
tail = tail->next;
scanf("%d", &tail->key);
tail->next = NULL;
}
}
// reverse list
list = reverseList(list);
// output list
pNode = list;
if(pNode == NULL)
printf("NULL\n");
else{
while(pNode != NULL){
/*最后一个元素后无空格,否则会出现格式错误(Presentation Error)*/
if(pNode->next != NULL)
printf("%d ", pNode->key);
else
printf("%d", pNode->key);
pNode = pNode->next;
};
printf("\n");
}
// free list
pNode = list;
while(pNode != NULL){
list = pNode->next;
free((void*) pNode);
pNode = list;
}
}
}
ListNode* reverseList(ListNode *pHead)
{
ListNode *pReverseHead = NULL;
ListNode *pPrev = NULL;
ListNode *pNode = pHead;
ListNode *pNext;
while(pNode != NULL){
pNext = pNode->next;
if(pNext == NULL)
pReverseHead = pNode;
pNode->next = pPrev;
pPrev = pNode;
pNode = pNext;
}
return pReverseHead;
}