forked from aishwarydewangan/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsingly.cpp
126 lines (106 loc) · 1.96 KB
/
singly.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
#include <iostream>
using namespace std;
int len;
struct ListNode {
int data;
ListNode *next;
};
void show(ListNode *head) {
if(len != 0) {
cout << "\n\tList: ";
while(head != NULL) {
cout << head->data << "->";
head = head->next;
}
cout << "NULL" << "\tLength: " << len << endl;
} else {
cout << "\n\tEmpty List";
}
}
void insert(ListNode **head) {
int data;
cout << "\nEnter data: ";
cin >> data;
if(len == 0 && *head == NULL) {
cout << "\n\tList is empty. Creating list";
*head = new ListNode;
(*head)->data = data;
(*head)->next = NULL;
} else {
int pos;
cout << "\nEnter position: ";
cin >>pos;
if(pos > len + 1) {
cout << "\n\tInvalid Position!";
return;
} else {
ListNode *node = new ListNode;
node->data = data;
if(pos == 1) {
node->next = *head;
*head = node;
} else {
ListNode *p = *head;
for(int i = 1; i < pos-1; i++)
p = p->next;
node->next = p->next;
p->next = node;
}
}
}
len++;
}
void remove(ListNode **head) {
ListNode *p = *head;
if(len == 0) {
cout << "\n\tNothing to remove!";
return;
}
if(len == 1) {
cout << "\n\tDeleting the only node of the list";
*head = NULL;
delete p;
} else {
int pos;
cout << "\nEnter position: ";
cin >> pos;
if(pos > len) {
cout << "\n\tInvalid Position!";
return;
} else {
if(pos == 1) {
(*head) = (*head)->next;
p->next = NULL;
delete p;
} else {
for(int i = 1; i < pos-1; i++)
p = p->next;
ListNode *node = p->next;
p->next = node->next;
delete node;
}
}
}
len--;
}
int main() {
int choice = 1;
ListNode *head = NULL;
len = 0;
while(choice) {
cout << "\n\n1.Insert\t2.Show\t3.Remove\t4.Exit";
cout << "\n\nEnter choice: ";
cin >> choice;
switch(choice) {
case 1: insert(&head);
break;
case 2: show(head);
break;
case 3: remove(&head);
break;
default: cout << "Exiting..." << endl;
choice = 0;
}
}
return 0;
}