-
Notifications
You must be signed in to change notification settings - Fork 0
/
revert.c
117 lines (93 loc) · 1.61 KB
/
revert.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
/*************************************************************************
> File Name: revert.c
> Author: simon_5s
> Mail: simon_5s@gmail.com
> Created Time: Fri 07 Feb 2014 05:02:55 PM HKT
************************************************************************/
#include<stdio.h>
#include<stdlib.h>
typedef struct _node
{
int data;
struct _node *next;
}node;
node *createnode()
{
node *pNode;
pNode = (node *)malloc(sizeof(node));
pNode->data = 0;
pNode->next = NULL;
return pNode;
}
int addnode(node *head, int data)
{
node *pNode;
if(head == NULL)
return -1;
pNode = (node *)malloc(sizeof(node));
pNode->data = data;
pNode->next = head->next;
head->next = pNode;
return;
}
int deletenode(node *head)
{
node *pNode;
if(head == NULL)
return -1;
while(head->next != NULL)
{
pNode = head->next;
head->next = head->next->next;
free(pNode);
}
free(head);
return;
}
void printnodes(const node *head)
{
while(head->next != NULL)
{
head = head->next;
printf("%d ", head->data);
}
printf("\n");
return;
}
int revert(node *head)
{
node *p1, *p2, *p3;
if(head == NULL || head->next == NULL || head->next->next == NULL)
return -1;
p1 = head->next;
p2 = p1->next;
p3 = p2->next;
p1->next = NULL;
while(p3 != NULL)
{
p2->next = p1;
p1 = p2;
p2 = p3;
p3 = p3->next;
}
p2->next = p1;
head->next = p2;
return;
}
void main()
{
node *head;
int i, data;
head=createnode();//head has no real data
for(i=0; i<20; i++)
{
data = rand() % 100;
addnode(head, data);
}
printnodes(head);
revert(head);
printnodes(head);
deletenode(head);
head = NULL;
return;
}