-
Notifications
You must be signed in to change notification settings - Fork 0
/
linked_list_Insertion.cpp
123 lines (116 loc) · 2.26 KB
/
linked_list_Insertion.cpp
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
#include <bits/stdc++.h>
using namespace std;
// Creating a template for creating linked list
class node
{
public:
int data;
node *next;
node(int data)
{
this->data = data;
this->next = NULL;
}
};
// Print the linked List
void print(node *head)
{
node *temp = head;
while (temp != NULL)
{
cout << temp->data << "-->";
temp = temp->next;
}
cout << "NULL" << endl;
}
// Function to add Insert data at head/initail
void insertAtHead(node *&head, int data)
{
node *temp = new node(data);
temp->next = head;
head = temp;
}
// Function to add Insert data at tail
void insertAtTail(node *&head, int data)
{
node *temp = new node(data);
if (head == NULL)
{
head = temp;
return;
}
node *p = head;
while (p->next != NULL)
{
p = p->next;
}
p->next = temp;
}
// Function to add data at the particular index
void insertAtIndex(node *&head, int data, int index)
{
node *temp = new node(data);
if (index == 0)
{
temp->next = head;
head = temp;
return;
}
node *p = head;
while (index != 1 && p != NULL)
{
index--;
p = p->next;
}
temp->next = p->next;
p->next = temp;
}
// Linked List insertion after a given Node
void insertAfterNode(node *prev_node, int data)
{
if (prev_node == NULL)
{
cout << "The given previous node cannot be NULL";
return;
}
node *temp = new node(data);
temp->next = prev_node->next;
prev_node->next = temp;
}
// Search a data in a linked list
bool search(node *head, int key)
{
node *temp = head;
while (temp != NULL)
{
if (temp->data == key)
{
return true;
}
temp = temp->next;
}
return false;
}
int main()
{
node *head = new node(10);
print(head);
insertAtHead(head, 20);
insertAtHead(head, 30);
print(head);
insertAtTail(head, 89);
insertAtTail(head, 189);
print(head);
insertAtIndex(head, 453, 0);
print(head);
if (search(head, 89))
{
cout << "The value found in the linked list\n";
}
else
{
cout << "The value not found in the linked list\n";
}
cout << "\n\n\n";
return 0;
}