-
Notifications
You must be signed in to change notification settings - Fork 0
/
reverseSLL.c
84 lines (69 loc) · 1.3 KB
/
reverseSLL.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>
typedef struct node
{
int data;
struct node* next;
} NODE;
NODE* getNode(int value)
{
NODE* temp = (NODE*)malloc(sizeof(NODE));
if (temp == NULL)
exit(42);
else
{
temp->data = value;
temp->next = NULL;
return temp;
}
}
NODE* insertEnd(int value, NODE* head)
{
NODE* temp = getNode(value);
if (head == NULL)
return temp;
else
{
NODE* cur = head;
while (cur->next != NULL)
cur = cur->next;
cur->next = temp;
return head;
}
}
NODE* reverseList(NODE* head)
{
NODE *prev = NULL, *cur = head, *next = NULL;
while (cur != NULL)
{
next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
return prev;
}
void printList(NODE* head)
{
while (head != NULL)
{
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
int main()
{
NODE* head = NULL;
head = insertEnd(1, head);
head = insertEnd(2, head);
head = insertEnd(3, head);
head = insertEnd(4, head);
head = insertEnd(5, head);
printf("Original list: ");
printList(head);
head = reverseList(head);
printf("Reversed list: ");
printList(head);
return 0;
}