-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinkedlist_insert.cc
108 lines (94 loc) · 1.71 KB
/
linkedlist_insert.cc
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
#include<iostream>
using namespace std;
struct node
{
int data;
struct node* next;
};
struct node* head;
void insert(int value)
{
if(head == NULL)
{
struct node* temp = (struct node*)malloc(sizeof(struct node));
temp->data = value;
temp->next = head;
head = temp;
}
else
{
struct node* ptr = head;
struct node* temp = (struct node*)malloc(sizeof(struct node));
temp->data = value;
temp->next = NULL;
while(ptr->next != NULL)
{
ptr = ptr->next;
}
ptr->next = temp;
}
}
void insert_at_loc(int loc, int value)
{
struct node* ptr = head;
struct node* temp = (struct node*)malloc(sizeof(struct node));
temp->data = value;
temp->next = NULL;
while(loc-- > 2)
ptr = ptr->next;
temp->next = ptr->next;
ptr->next = temp;
}
void traverse()
{
struct node* ptr = head;
while(ptr != NULL)
{
cout<<"["<<ptr->data<<"] -> ";
ptr = ptr->next;
}
cout<<endl;
}
int main()
{
head = NULL;
int flag = 1;
while(flag)
{
int n,ch,x;
cout<<"Press 1 to enter in regular fashion\nPress 2 to enter at specific position\nEnter your Choice = ";
cin>>ch;
if(ch == 1)
{
cout<<"Enter N = ";
cin>>n;
while(n-- > 0)
{
cout<<"\nEnter data = ";
cin>>x;
insert(x);
traverse();
}
}
else if(ch == 2)
{
int loc;
cout<<"Enter location = ";
cin>>loc;
cout<<"Enter data = ";
cin>>x;
insert_at_loc(loc,x);
traverse();
}
else
cout<<"You've entered wrong choice\n";
char ch2;
cout<<"\nWant to Continue ?(y/n) = ";
cin>>ch2;
if(ch2 == 'y')
flag = 1;
else
flag = 0;
}
return 0;
}