-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathlinkedlist_simple.c
107 lines (91 loc) · 1.71 KB
/
linkedlist_simple.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
#include <stdio.h>
#include <stdlib.h>
struct NODE
{
int data;
struct NODE *next;
};
typedef struct NODE *node;
void getnode(node *n)
{
*n = (struct NODE *)malloc(sizeof(struct NODE));
}
//for insert in the beginning set pos as 0
//for insert in the end set pos as negative number say -1
void insert(node *n, int pos, int x)
{
while(*n != NULL && pos != 0)
{
n = &((*n)->next);
pos--;
}
node temp = *n;
getnode(n);
(*n)->data = x;
(*n)->next = temp;
}
void display(node n)
{
if (n == NULL)
{
printf("no elements present");
}
while(n != NULL)
{
printf("-> %d ", n->data);
n = n->next;
}
printf("\n\n");
}
int delete(node *n, int pos)
{
while (*n != NULL)
{
if (pos == 0)
{
node temp = *n;
*n = (*n)->next;
int temp2 = temp->data;
free(temp);
return temp2;
}
pos--;
}
return 0;
}
int main()
{
node a = NULL;
while (1)
{
int n;
printf("1 - insert, 2 - display, 3 - delete : ");
scanf("%d", &n);
if (n == 1)
{
int d, pos;
printf("Enter int: ");
scanf("%d", &d);
printf("Enter position : ");
scanf("%d", &pos);
printf("\n");
insert(&a, pos, d);
}
else if (n == 2)
{
display(a);
}
else if (n == 3)
{
int pos;
printf("Enter position : ");
scanf("%d", &pos);
printf("\n");
delete(&a, pos);
}
else
{
return 0;
}
}
}