forked from nitind2411/hacktoberfest-2022-DSA-CP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinsertionInLinkedList.cpp
114 lines (96 loc) · 1.81 KB
/
insertionInLinkedList.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
// Alternate method to declare the class
// in order to minimize the
// memory allocation work
#include <bits/stdc++.h>
using namespace std;
class node {
public:
int data;
node* next;
// A constructor is called here
node(int value)
{
// It automatic assigns the
// value to the data
data = value;
// Next pointer is pointed to NULL
next = NULL;
}
};
// Function to insert an element
// at head position
void insertathead(node*& head, int val)
{
node* n = new node(val);
n->next = head;
head = n;
}
// Function to insert a element
// at a specified position
void insertafter(node* head, int key, int val)
{
node* n = new node(val);
if (key == head->data) {
n->next = head->next;
head->next = n;
return;
}
node* temp = head;
while (temp->data != key) {
temp = temp->next;
if (temp == NULL) {
return;
}
}
n->next = temp->next;
temp->next = n;
}
// Function to insert an
// element at the end
void insertattail(node*& head, int val)
{
node* n = new node(val);
if (head == NULL) {
head = n;
return;
}
node* temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = n;
}
// Function to print the
// singly linked list
void print(node*& head)
{
node* temp = head;
while (temp != NULL) {
cout << temp->data << " -> ";
temp = temp->next;
}
cout << "NULL" << endl;
}
// Main function
int main()
{
// Declaring an empty linked list
node* head = NULL;
insertathead(head, 1);
insertathead(head, 2);
cout << "After insertion at head: ";
print(head);
cout << endl;
insertattail(head, 4);
insertattail(head, 5);
cout << "After insertion at tail: ";
print(head);
cout << endl;
insertafter(head, 1, 2);
insertafter(head, 5, 6);
cout << "After insertion at a given position: ";
print(head);
cout << endl;
return 0;
}
// contributed by divyanshmishra101010