-
Notifications
You must be signed in to change notification settings - Fork 342
/
Delete_element_from_circular_linkedlist.cpp
118 lines (101 loc) · 2.39 KB
/
Delete_element_from_circular_linkedlist.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
#include <bits/stdc++.h>
using namespace std;
// Structure of a node
class Node {
public:
int data;
Node* next;
};
// Insert a node at the beginning
void pushBeg(Node **head, int data){
Node *newNode = new Node();
newNode->data = data;
newNode->next = *head;
if(*head != NULL){
Node *temp = *head;
while(temp->next != *head){
temp = temp->next;
}
temp->next = newNode;
} else{
newNode->next = newNode;
}
*head = newNode;
}
// Printing nodes
void printList(Node *head){
Node *temp = head;
if(head != NULL){
do{
cout << temp->data << " ";
temp = temp->next;
} while(temp != head);
}
cout << endl;
}
// Delete a given node
void deleteNode(Node **head, int key){
int pos = 0;
if(*head == NULL){
cout << "List not initialized" << endl;
return;
}
Node *curr = *head, *prev;
if((*head)->data == key){
if((*head)->next != *head){
curr = *head;
while(curr->next != *head){
curr = curr->next;
}
curr->next = (*head)->next;
*head = (*head)->next;
return;
}
else {
*head = NULL;
cout << "List is Empty" << endl;
exit(0);
}
}
else if((*head)->data != key && (*head)->next == NULL){
cout << "Element not found" << endl;
return;
}
curr = *head;
while(curr->next != *head && curr->data != key){
prev = curr;
curr = curr->next;
}
if(curr->data == key){
prev->next = prev->next->next;
free(curr);
}
else{
cout << "Element not found" << endl;
}
}
int main(){
int input, ele;
//Initialize an empty list
Node *head = NULL;
//Change the input here
cout << "Enter elements to insert or '-1' to exit: ";
cin >> input;
while(input != -1){
pushBeg(&head, input);
cin >> input;
}
//Printing list before deletion
cout << "\nList before deletion: ";
printList(head);
cout << endl;
//Deleting element
cout << "Enter element to delete: ";
cin >> ele;
deleteNode(&head, ele);
//Printing list after deletion
cout << "List after deletion: ";
printList(head);
cout << endl;
return 0;
}