-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLinkedList_insert.cpp
More file actions
110 lines (103 loc) · 1.97 KB
/
LinkedList_insert.cpp
File metadata and controls
110 lines (103 loc) · 1.97 KB
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
#include <bits/stdc++.h>
using namespace std;
class node
{
public:
int data;
node *next;
};
void PrintList(node *input)
{
while (input != NULL)
{
cout << input->data << " ";
input = input->next;
}
cout << endl;
}
void Insert_at_Begining(node **head)
{
node *push = new node;
push->next = *head;
int dat;
cout << "Enter data at the first node \n";
cin >> dat;
push->data = dat;
*head = push;
}
void Insert_at_End(node **last, node *last_node)
{
node *add = new node;
add->next = NULL;
cout << "Enter data at the last node\n";
int data;
cin >> data;
add->data = data;
last_node->next = add;
*last = add;
}
int Insert_pos(node *head)
{
cout << "enter the position you want to insert\n";
int pos;
cin >> pos;
for (int i = 2; i < pos; i++)
{
head = head->next;
}
if (head == NULL)
{
return 1;
}
else if (pos == 1)
{
return 0;
}
else
{
cout << "Enter the data to be inserted at " << pos << " node\n";
int data;
cin >> data;
node *position = new node;
position->data = data;
position->next = head->next;
head->next = position;
}
return 2;
}
int main()
{
node *head = new node;
node *second = new node;
node *third = new node;
node *fourth = new node;
node *last = new node;
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = fourth;
fourth->data = 4;
fourth->next = last;
last->data = 5;
last->next = NULL;
int pos_check = 9;
PrintList(head);
cout << endl;
pos_check = Insert_pos(head);
if (pos_check == 0)
{
Insert_at_Begining(&head);
}
else if (pos_check == 1)
{
Insert_at_End(&last, last);
}
PrintList(head);
cout << endl;
delete head;
delete second;
delete last;
return 0;
}