forked from Sai-02/Data-Structures-using-C
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInsertion_in_doubly_LinkedList.c
99 lines (92 loc) · 2.06 KB
/
Insertion_in_doubly_LinkedList.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
#include <stdio.h>
#include <stdlib.h>
struct node
{
int info;
struct node *next;
struct node *prev;
};
struct node *insertValue(struct node *, int, int);
int main()
{
int n;
scanf("%d", &n);
struct node *head = (struct node *)malloc(sizeof(struct node));
head->next = NULL;
head->prev = NULL;
struct node *current = head;
// struct node* previous=NULL;
for (int i = 0; i < n; i++)
{
int value;
scanf("%d", &value);
if (i == 0)
{
current->info = value;
current->prev = NULL;
}
else
{
struct node *new = (struct node *)malloc(sizeof(struct node));
new->info = value;
new->prev = current;
new->next = NULL;
current->next = new;
current = current->next;
}
}
int value;
int index;
scanf("%d %d", &value, &index);
head = insertValue(head, value, index);
current = head;
while (current->next != NULL)
{
printf("%d ", current->info);
current = current->next;
}
printf("%d\n", current->info);
while (current != NULL)
{
printf("%d ", current->info);
current = current->prev;
}
return 0;
}
struct node *insertValue(struct node *head, int value, int index)
{
if (head == NULL)
{
return NULL;
}
struct node *new = (struct node *)malloc(sizeof(struct node));
new->info = value;
new->prev = NULL;
new->next = NULL;
if (index == 0)
{
new->next = head;
head->prev = new;
return new;
}
int i = 0;
struct node *current = head;
struct node *previous;
while (current != NULL)
{
if (i == index)
{
previous->next = new;
new->prev = previous;
new->next = current;
current->prev = new;
return head;
}
i++;
previous = current;
current = current->next;
}
previous->next = new;
new->prev = previous;
return head;
}