-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathdelete-node-double-list.cpp
92 lines (82 loc) · 1.96 KB
/
delete-node-double-list.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
// http://www.geeksforgeeks.org/delete-a-node-in-a-doubly-linked-list/
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node *left, *right;
Node(int data) {
this->data = data;
this->left = NULL;
this->right = NULL;
}
};
void deleteNode(Node *head, int data);
Node* addNode(Node *head, int data);
void printLeftToRight(Node *head);
void printLeftToRight(Node *head);
void deleteNode(Node *head, int data) {
if (head == NULL)
return;
Node *ptr = head;
while (ptr != NULL && ptr->data != data)
ptr = ptr->right;
// element not in list
if (ptr == NULL) {
cout<<endl<<"element not in list..";
return;
}
// element is last node
if (ptr->right == NULL) {
ptr->left->right = NULL;
return;
}
// element is anything except last
ptr->data = ptr->right->data;
ptr->right = ptr->right->right;
if (ptr->right != NULL)
ptr->right->left = ptr;
}
Node* addNode(Node *head, int data) {
if (head == NULL)
return new Node(data);
Node *ptr = head;
while (ptr->right != NULL)
ptr = ptr->right;
ptr->right = new Node(data);
ptr->right->left = ptr;
return head;
}
void printLeftToRight(Node *head) {
if (head == NULL)
return;
while (head != NULL) {
cout<<head->data<<" ";
head = head->right;
}
}
void printRightToLeft(Node *head) {
if (head == NULL)
return;
while (head != NULL) {
cout<<head->data<<" ";
head = head->left;
}
}
int main() {
Node *head = NULL;
head = addNode(head, 1);
head = addNode(head, 2);
head = addNode(head, 3);
head = addNode(head, 4);
head = addNode(head, 5);
cout<<"original: ";
printLeftToRight(head);
cout<<endl<<"after deleting 1,3,5: ";
deleteNode(head, 1);
deleteNode(head, 3);
deleteNode(head, 5);
printLeftToRight(head);
cout<<endl;
return 0;
}