forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 1
/
reverse_linked_list.c
121 lines (100 loc) · 2.07 KB
/
reverse_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
115
116
117
118
119
120
121
/* GIVEN A LINKED LIST ,TASK IS TO REVERSE THE LINKED LIST BY REVERSING THE LINKS */
#include<stdio.h>
#include<malloc.h>
/* structure containing data part and link part */
struct node
{
int data;
struct node *link;
};
void append(struct node** ,int);
void display(struct node*);
void reverse(struct node **);
int main()
{
struct node* head = NULL;
int i,p,c;
printf("ENTER THE NUMBER OF ELEMENTS IN LINKED LIST ");
scanf("%d",&i);
for(p=i;p>0;p--)
{
printf("\nENTER THE ELEMENT ");
scanf("%d",&c);
append(&head,c);
}
printf("LINKED LIST: \n");
display(head);
reverse(&head);
printf("\nREVERSED LINKED LIST: \n");
display(head);
return 0;
}
/*adds node at the end of a linked list*/
void append(struct node **head_ref,int num)
{
struct node *temp,*r;
if(*head_ref==NULL)
{
temp=(struct node*)malloc(sizeof(struct node));
temp->data=num;
temp->link=NULL;
*head_ref=temp;
}
else
{
temp=*head_ref;
/* go to last node */
while(temp->link != NULL)
{
temp = temp->link;
}
/* add node at end */
r=(struct node*)malloc(sizeof(struct node));
r->data=num;
r->link=NULL;
temp->link=r;
}
}
/* displays the content of linked list */
void display(struct node *head_ref)
{
/* traverse the entire linked list */
while(head_ref!=NULL)
{
printf("%d\t",head_ref->data);
head_ref=head_ref->link;
}
}
/*reverses the linked list*/
void reverse(struct node **head_ref)
{
struct node *cur,*prev,*next;
cur=*head_ref;
prev=NULL;
next=NULL;
/*traverse the entire linked list*/
while(cur!=NULL)
{
next=cur->link;
/*reverse current node pointers*/
cur->link=prev;
/*move pointers one position ahead*/
prev=cur;
cur=next;
}
*head_ref=prev;
}
/*
SAMPLE INPUT OUTPUT
ENTER THE NUMBER OF ELEMENTS IN LINKED LIST 5
ENTER THE ELEMENT 4
ENTER THE ELEMENT 12
ENTER THE ELEMENT 6
ENTER THE ELEMENT 25
ENTER THE ELEMENT 41
LINKED LIST:
4 12 6 25 41
REVERSED LINKED LIST:
41 25 6 12 4
TIME COMPLEXITY -> O(n)
SPACE COMPLEXITY -> O(1)*/