-
Notifications
You must be signed in to change notification settings - Fork 2
/
delete_a_data.c
114 lines (86 loc) · 1.94 KB
/
delete_a_data.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
#include<stdio.h>
#include<stdlib.h>
struct Node {
int data;
struct Node *next;
}*head;
typedef struct Node node;
node * getNode() {
node * temp;
temp = (node*) malloc(sizeof(node));
return temp;
}
int getCurrentSize() {
node * temp = head;
int count = 0;
while(temp != NULL) {
count++;
temp = temp -> next;
}
return count;
}
void insert(int item) {
node * temp = getNode();
temp -> data = item;
temp -> next = NULL;
if(head == NULL) head = temp;
else {
node * curr_node = head;
while(curr_node -> next != NULL) curr_node = curr_node -> next;
curr_node -> next = temp;
}
}
void delete_nth_node(int pos) {
if(pos == 1)
head = head -> next;
else {
node * curr_node = head;
node * prev = curr_node;
while(--pos) {
prev = curr_node;
curr_node = curr_node -> next;
}
int deleted = curr_node -> data;
printf("%dth node deleted...\n", deleted);
prev -> next = curr_node -> next;
}
}
void delete_an_item(int item) {
node * temp = head;
int count = 0;
while(temp != NULL) {
count++;
if(temp -> data == item) break;
temp = temp -> next;
}
if(count > getCurrentSize() || count == 0) {
printf("item doesn't exist...\n");
}
else {
delete_nth_node(count);
printf("%d deleted...\n", item);
}
}
void show() {
node * temp = head;
while(temp != NULL) {
printf("%d ", temp -> data);
temp = temp -> next;
}
printf("\n");
}
int main()
{
int size;
for(int i = 1; i <= 10; i++) insert(i);
show();
size = getCurrentSize();
printf("Current size: %d\n", size);
// delete_nth_node(5);
// show();
delete_an_item(10);
show();
size = getCurrentSize();
printf("Current size: %d\n", size);
return 0;
}