-
Notifications
You must be signed in to change notification settings - Fork 0
/
deletioncll.c
105 lines (99 loc) · 2.24 KB
/
deletioncll.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
// Deletion from a c.l.l by Vishruth Codes
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *link;
} * head;
// Function to append elements into c.l.l.
void append(int a[], int n)
{
struct node *temp, *last;
head = (struct node *)malloc(sizeof(struct node));
head->data = a[0];
head->link = head;
last = head;
for (int i = 1; i < n; i++)
{
temp = (struct node *)malloc(sizeof(struct node));
temp->data = a[i];
temp->link = last->link;
last->link = temp;
last = temp;
}
printf("\nThe C.L.L is successfully created!");
}
// function to display elements of c.l.l.
void display(struct node *h)
{
struct node *p;
p = h;
do
{
printf("%d, ", p->data);
p = p->link;
} while (p != h);
}
// function to calculate the length of c.l.l.
int length(struct node *h)
{
struct node *p;
int count = 0;
p = h;
do
{
count++;
p = p->link;
} while (p != h);
return count;
}
// Function to delete elements of c.l.l.
void delete (struct node *h, int pos)
{
struct node *p;
p = h;
// if pos in not present in c.l.l
if (pos < 0 || pos >= length(head))
{
printf("\nInvalid position!");
return;
}
// if it's the starting position (head)
else if (pos == 0)
{
do
{
p = p->link;
} while (p->link != h);
printf("%d is successfully deleted!", h->data);
p->link = h->link;
free(h);
head = p->link;
}
else // for all other cases
{
struct node *l;
for (int i = 0; i < pos; i++)
{
l = p;
p = p->link;
}
printf("%d is successfully deleted!", p->data);
l->link = p->link;
free(p);
}
}
int main()
{
int len = 5, n;
int ar[] = {1, 2, 3, 4, 5};
append(ar, len);
printf("\nThe c.l.l is: ");
display(head);
printf("\nEnter the location (0-%d) at which you wish to delete: ", length(head));
scanf("%d", &n);
delete (head, n);
printf("\nThe c.l.l after deletion is: ");
display(head);
}