-
Notifications
You must be signed in to change notification settings - Fork 0
/
SLL.cpp
143 lines (143 loc) · 2.29 KB
/
SLL.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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
#include <iostream>
#define endl '\n'
using namespace std;
struct node
{
int data;
struct node* next;
};
void insert(node** head,int data,int pos)
{
struct node *p;
node* newNode=new node;
int k=1;
if(!newNode)
{
cout<<"Memory allocation error\n";
return;
}
newNode->data=data;
p=*head;
if(pos==1)
{
newNode->next=*head;
*head=newNode;
}
else
{
while((p->next!=NULL) && k<pos-1)
{
//q=p;
p=p->next;
k++;
}
if(p->next==NULL) //insert at end
{
p->next=newNode;
newNode->next=NULL;
}
else
{
newNode->next=p->next;
p->next=newNode;
}
}
}
void del(node** head,int pos)
{
struct node *p;
p=*head;
int k=1;
if(p==NULL)
{
cout<<"List empty\n";
return;
}
if(pos==1)
{
*head=(*head)->next;
delete p;
}
else
{
while((p->next!=NULL)&& k<pos-1)
{
//q=p;
p=p->next;
k++;
}
if(p->next==NULL)
{
cout<<"Position exceeds length of list\n";
return;
}
else
{
node *temp = p->next;
p->next=temp->next;
delete temp;
}
}
}
void traversal(node** head)
{
node* temp=new node;
temp=*head;
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp=temp->next;
}
cout<<endl;
delete temp;
}
node* revList(node **head) {
node *temp = NULL,*nextNode = NULL;
while(*head != NULL) {
nextNode = (*head)->next;
(*head)->next = temp;
temp = *head;
*head = nextNode;
}
return temp;
}
void deleteList(node** head)
{
node* p=*head;
if(p==NULL)
return;
while(p->next!=NULL)
{
node *temp=p->next;
p->next=temp->next;
delete temp;
}
delete p;
}
int main()
{
int pos,val,ch;
struct node* head=NULL;
do
{
cout<<"1. Insertion\n2. Deletion\n3. Traversal\n4. Reversal\n5. Exit\n";
cin>>ch;
switch (ch)
{
case 1: cout<<"Enter value and position\n";
cin>>val>>pos;
insert(&head,val,pos);
break;
case 2: cout<<"Enter position\n";
cin>>pos;
del(&head,pos);
break;
case 3: traversal(&head);
break;
case 4: head = revList(&head);
break;
}
}while(ch!=5);
deleteList(&head);
return 0;
}