-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathVishruthS_Q22_ReverseLinkedList.c
99 lines (84 loc) · 1.78 KB
/
VishruthS_Q22_ReverseLinkedList.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
//CSL201 DATA STRUCTURES LAB ----- VISHRUTH S, CS3A, 61
//CYCLE 3 QUESTION 2
//To Reverse a singly linked list
#include <stdio.h>
#include <stdlib.h>
// Node contains data and link to next node
struct Node
{
int data;
struct Node *link;
};
// Head pointer to linked list
struct Node *head = NULL;
// ======= REVERSE FUNCTIONS =======//
// METHOD 1: Iterative
// Time complexity: O(n)
void reverse_iterative()
{
struct Node *prev, *current, *next;
prev = NULL;
current = head;
while (current != NULL)
{
next = current->link;
current->link = prev;
prev = current;
current = next;
}
head = prev;
}
// METHOD 2: Recursive
// Time complexity: O(n)
void reverse_recursive(struct Node *ptr)
{
if (ptr->link == NULL)
{
head = ptr;
return;
}
reverse_recursive(ptr->link);
struct Node *temp = ptr->link;
temp->link = ptr;
ptr->link = NULL;
}
void insertAtBeginning(int);
void display();
// ==== MAIN FUNCTION ====//
int main()
{
insertAtBeginning(12);
insertAtBeginning(34);
insertAtBeginning(18);
insertAtBeginning(42);
insertAtBeginning(15);
insertAtBeginning(24);
insertAtBeginning(20);
printf("\nBefore reverse: ");
display();
reverse_iterative();
// reverse_recursive();
printf("\nAfter reverse: ");
display();
return 0;
}
// ===== Auxillary functions =====//
// To insert elements at front
void insertAtBeginning(int data)
{
struct Node *ptr = (struct Node *)malloc(sizeof(struct Node));
ptr->data = data;
ptr->link = head;
head = ptr;
}
// TO display the linked list
void display()
{
printf("\n");
struct Node *ptr = head;
while (ptr != NULL)
{
printf("%d -> ", ptr->data);
ptr = ptr->link;
}
}