-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinsertAfterSearch.c
141 lines (122 loc) · 2.57 KB
/
insertAfterSearch.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
132
133
134
135
136
137
138
139
140
141
//search for an element and insert a new node after it
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *prev;
struct node *next;
} *head, *tail;
struct node *CreateNode(int data)
{
struct node *n;
n=(struct node*)malloc(sizeof(struct node));
if(n==NULL)
{
printf("memory not allocated");
return NULL;
}
n->data=data;
n->next=NULL;
n->prev=NULL;
return n;
}
struct node *CreateList(int n)
{
int data;
printf(" Input data for node 1 : ");
scanf("%d", &data);
struct node *newNode=CreateNode(data);
if (newNode == NULL) return NULL;
head=newNode;
tail = head;
for (int i=2; i<=n; i++)
{
printf(" Input data for node %d : ", i);
scanf("%d", &data);
struct node *newNode=CreateNode(data);
if (newNode == NULL) return head;
newNode->prev = tail;
tail->next = newNode;
tail = newNode;
}
return head;
}
void DisplayList() {
struct node *temp=head;
if (head == NULL)
{
printf("List is empty. \n");
return;
}
printf("The list is: ");
while (temp != NULL)
{
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
struct node *insertAfterKey(struct node *ptr)
{
struct node *temp=ptr->next;
int data;
printf("Enter element that you want to inssert: ");
scanf("%d",&data);
struct node *newNode=CreateNode(data);
if(temp==NULL)
{
ptr->next=newNode;
newNode->prev=temp;
return head;
}
newNode->next=temp;
newNode->prev=ptr;
ptr->next=newNode;
temp->prev=newNode;
printf("Node added. \n");
return head;
}
void search()
{
struct node *ptr=head;
if (ptr==NULL)
{
printf("list is empty \n");
return;
}
int key, i=0, flag=1;
printf("Enter element you want to search: ");
scanf("%d", &key);
while (ptr != NULL)
{
if(ptr->data == key)
{
printf("Item found at location %d \n", i + 1);
flag = 0;
break;
}
i++;
ptr = ptr->next;
}
DisplayList();
if(flag == 1)
{
printf("Item not found\n");
return;
}
else{
head=insertAfterKey(ptr);
}
}
int main() {
head = NULL;
tail = NULL;
int n;
printf(" Input the number of nodes for doubly linked list : ");
scanf("%d", &n);
CreateList(n);
DisplayList();
search();
DisplayList();
return 0;
}