forked from VaibhavD74/HacktoberFest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
implementlinkedlist.cpp
104 lines (102 loc) · 2.37 KB
/
implementlinkedlist.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
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
struct node
{
int data;
node *next;
};
void display(node *head)
{
cout<<"The linked list is: ";
node *temp=head;
while(temp!=NULL)
{
cout<<temp->data<<"--->";
temp=temp->next;
}
cout<<endl;
}
int main()
{
cout<<"Enter 1 to insert a node\nEnter 2 to delete a node\nEnter 0 to exit"<<endl;
int a;
cin>>a;
int n=0;
node *head=NULL;
while(a!=0)
{
if(a==1)
{
cout<<"Enter data to insert: ";
int data;
cin>>data;
if(head==NULL)
{
node *nn=new node();
nn->data=data;
nn->next=NULL;
head=nn;
}
else
{
node *temp,*nn;
temp=head;
while(temp->next!=NULL)
temp=temp->next;
nn=new struct node();
nn->data=data;
nn->next=NULL;
temp->next=nn;
}
display(head);
n++;
}
else if(a==2)
{
cout<<"Enter position to delete: ";
int pos;
cin>>pos;
node *nn,*temp;
if(head==NULL)
{
cout<<"Linked list is empty!";
}
nn = temp = head;
if (pos != 1 && pos != n)
{
for (int i = 1; i < pos + 1; i++)
{
nn = nn->next;
temp = nn;
}
nn = head;
for (int i = 1; i < pos; i++)
{
if (i == (pos - 1))
nn->next = temp;
else
nn = nn->next;
}
}
else if (pos == 1)
{
head = nn->next;
}
else
{
for (int i = 1; i < n; i++)
{
if (i == (n - 1))
nn->next = NULL;
else
nn = nn->next;
}
}
display(head);
}
cout<<"Enter 1 to insert a node\nEnter 2 to delete a node\nEnter 0 to exit"<<endl;
cin>>a;
}
return 0;
}