-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram4.cpp
More file actions
131 lines (105 loc) · 2.95 KB
/
Program4.cpp
File metadata and controls
131 lines (105 loc) · 2.95 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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
// Program to create a linked list and implement insertion and deletion operations on it.
#include <iostream>
using namespace std;
// Define a node structure
struct Node {
int data;
Node* next;
Node(int val) {
data = val;
next = nullptr;
}
};
// Linked List class with insertion and deletion operations
class LinkedList {
private:
Node* head;
public:
LinkedList() {
head = nullptr;
}
// Function to insert a node at the beginning of the list
void insertAtBeginning(int value) {
Node* newNode = new Node(value);
newNode->next = head;
head = newNode;
}
// Function to insert a node at the end of the list
void insertAtEnd(int value) {
Node* newNode = new Node(value);
if (head == nullptr) {
head = newNode;
return;
}
Node* temp = head;
while (temp->next != nullptr) {
temp = temp->next;
}
temp->next = newNode;
}
// Function to delete a node with a specific value
void deleteNode(int value) {
if (head == nullptr) {
cout << "List is empty!" << endl;
return;
}
// If the node to be deleted is the head
if (head->data == value) {
Node* temp = head;
head = head->next;
delete temp;
return;
}
Node* temp = head;
while (temp->next != nullptr && temp->next->data != value) {
temp = temp->next;
}
// If the value is not found
if (temp->next == nullptr) {
cout << "Value not found!" << endl;
return;
}
// Delete the node
Node* nodeToDelete = temp->next;
temp->next = temp->next->next;
delete nodeToDelete;
}
// Function to display the list
void display() {
if (head == nullptr) {
cout << "List is empty!" << endl;
return;
}
Node* temp = head;
while (temp != nullptr) {
cout << temp->data << " -> ";
temp = temp->next;
}
cout << "NULL" << endl;
}
};
// Main function to test the Linked List operations
int main() {
cout<<"Umesh Patel\nEnrollment Number: 0126AL231140\n";
LinkedList list;
// Insert elements at the beginning
list.insertAtBeginning(10);
list.insertAtBeginning(20);
list.insertAtBeginning(30);
// Display the list
cout << "List after insertion at the beginning: ";
list.display();
// Insert elements at the end
list.insertAtEnd(40);
list.insertAtEnd(50);
// Display the list
cout << "List after insertion at the end: ";
list.display();
// Delete a node with value 20
list.deleteNode(20);
cout << "List after deleting node with value 20: ";
list.display();
// Delete a node with value 100 (not in the list)
list.deleteNode(100);
return 0;
}