forked from ShreyaDhir/HacktoberFest2020
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RotateLinkedList.c
131 lines (116 loc) · 2.42 KB
/
RotateLinkedList.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
122
123
124
125
126
127
128
129
130
131
/*
Rotates a linked list by a value k.
*/
#include<stdio.h>
#include<stdlib.h>
struct node //Defining node structure
{
struct node* prev;
int data;
struct node* next;
}*head = NULL;
int isEmpty() //to check if linked list in empty
{
if (!head)
return 1;
return 0;
}
void create() //to create the list
{
int ch, data;
do
{
printf("\nEnter data.\t");
scanf("%d", &data);
struct node* NEW = (struct node*)malloc(sizeof(struct node));
if (!NEW)
{
printf("\nMemory cannot be assigned due to insufficient storage!\n");
return;
}
NEW->prev = NULL;
NEW->next = NULL;
struct node* ptr = head;
if (!ptr)
{
NEW->data = data;
head = NEW;
printf("\nData insertion successful!\n");
}
else
{
while (ptr->next != NULL)ptr = ptr->next;
NEW->prev = ptr;
NEW->data = data;
ptr->next = NEW;
printf("\nData insertion successful!\n");
}
printf("Enter 1 to continue data entry.\nEnter 0 to terminate data entry.\n");
scanf("%d", &ch);
} while (ch);
}
void display() //to display the list
{
struct node* ptr = head;
if (!ptr)
{
printf("\nEmpty list!\nNothing to print.\n");
return;
}
printf("List :\n");
while (ptr)
{
printf(" %d ", ptr->data);
ptr = ptr->next;
}
printf("\n");
}
int count() //to count no of node present in the list.
{
int c = 0;
struct node* ptr = head;
while (ptr)
{
ptr = ptr->next;
c++;
}
return c;
}
void rotate() //to rotate the list
{
int k;
printf("Enter k.\t");
scanf("%d", &k);
int c = count();
if (k > c)
{
printf("Invalid value for k.\n");
exit(0);
}
if(k == 1)
{
printf("Rotation successful!\n");
return;
}
struct node* ptr1 = head;
struct node* ptr2 = head;
int i = 0;
while (ptr2->next)ptr2 = ptr2->next;
while (i++ < k)ptr1 = ptr1->next;
ptr2->next = head;
head->prev = ptr2;
ptr1->prev->next = NULL;
ptr1->prev = NULL;
head = ptr1;
printf("Rotation successful!\n");
return;
}
int main()
{
int i;
create();
display();
rotate();
display();
return 0;
}