-
Notifications
You must be signed in to change notification settings - Fork 364
/
Reverse a singly linked list.c
114 lines (57 loc) · 1.33 KB
/
Reverse a singly linked list.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
Reversing a linked list using iterative approach
#include<stdio.h>
#include<stdlib.h>
//Node structure of the linked list
struct Node{
int value;
struct Node* next;
};
//Reverse the linked list function
void reverse(struct Node** head)
{
struct Node* p=NULL;
struct Node* c=*head;
struct Node* next=NULL;
while(c!=NULL){
//stroring the next address of current node
next=c->next;
//reversing the current node's ponter
c->next=p;
//moving the pointer on position ahead
p=c;
c=next;
}
*head=p;
}
//To push a node in linked list
void push(struct Node** head, int val){
struct Node* newnode=(struct Node*)malloc(sizeof(struct Node));
newnode->value=val;
newnode->next=(*head);
*head=newnode;
}
//Printing function-to print the linked list
void show(struct Node* h){
struct Node* t=h;
while(t!=NULL){
printf("%d ", t->value);
t=t->next;
}
}
int main()
{
//empty list
struct Node* h = NULL;
push(&h, 25);
push(&h, 36);
push(&h, 44);
push(&h, 50);
push(&h, 17);
push(&h, 66);
printf("Linked list before reversal:\n");
show(h);
reverse(&h);
printf("\nLinked list after reversal:\n");
show(h);
}
Time Complexity of reversing a linked list is O(n)