-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLinkedLists.cpp
More file actions
115 lines (108 loc) · 2.05 KB
/
LinkedLists.cpp
File metadata and controls
115 lines (108 loc) · 2.05 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
111
112
113
114
115
#include<bits/stdc++.h>
using namespace std;
//Declaring a Linked List
struct Node{
int data;
struct Node* next;
};
//Creating a Head Pointer
struct Node* head = NULL;
//Inserting a Node at the Start
void insertAtStart(int n){
struct Node* newNode = new Node;
newNode->data = n;
newNode->next = head;
head = newNode;
}
//Inserting a Node at the End
void insertAtEnd(int n){
struct Node* newNode = new Node;
struct Node* temp = head;
if(head == NULL){
head = newNode;
newNode->data = n;
newNode->next = NULL;
}
else{
while(temp->next != NULL){
temp = temp->next;
}
temp->next = newNode;
newNode->data = n;
newNode->next = NULL;
}
delete temp;
}
//Displaying All Items in the Linked List
void display(){
struct Node* temp = head;
if(head == NULL){
cout << "List is empty." << endl;
}
else{
while(temp != NULL){
cout << temp->data << "->";
temp = temp->next;
}
cout << "NULL" << endl;
}
delete temp;
}
//Deleting the First Element
void deleteFirst(){
struct Node* temp = head;
if(head == NULL){
cout << "List is empty." << endl;
}
else{
head = head->next;
}
delete temp;
}
//Deleting the Last Element
void deleteLast(){
if(head == NULL){
cout << "List is empty." << endl;
}
else if(head->next == NULL){
delete head;
}
else{
struct Node* second_last = head;
while (second_last->next->next != NULL)
second_last = second_last->next;
delete (second_last->next);
second_last->next = NULL;
}
}
int main(){
int i = -1;
int elem;
cout << "LINKED LIST:" << endl;
while(i != 0){
cout << "ENTER\n1.INSERT AT THE START\n2.INSERT AT THE BACK\n3.DISPLAY ALL ELEMENTS\n4.DELETE FIRST ELEMENT\n5.DELETE LAST ELEMENT\n0.QUIT PROGRAM" << endl;
cin >> i;
switch(i){
case 1:
cout << "Enter Element" <<endl;
cin >> elem;
insertAtStart(elem);
break;
case 2:
cout << "Enter Element" <<endl;
cin >> elem;
insertAtEnd(elem);
break;
case 3:
display();
break;
case 4:
deleteFirst();
break;
case 5:
deleteLast();
break;
}
}
return 0;
}