-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinkedList_1.cpp
122 lines (104 loc) · 1.73 KB
/
LinkedList_1.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
#include<iostream>
using namespace std;
class Node
{
private:
int data;
Node *next;
Node *head;
public:
Node():head(NULL){}
void AppendAtEnd(int a)
{
Node *newNode = new Node;
newNode->data = a;
newNode->next = NULL;
//if list is empty
if (head == NULL)
{
head = newNode;
//head->next = NULL;
return;
}
//if list is not empty, iterate to the end of the list
Node *temp = head;
while (temp->next != NULL)
{
temp = temp->next;
}
//add the new node to the list
temp->next = newNode;
//temp->next = NULL;
}
void Print()
{
Node *temp = head;
//if list is empty
if (temp == NULL)
{
cout<<"List empty!\n";
return;
}
//if list is not empty
while (temp != NULL)
{
cout<<temp->data<<"-->";
temp = temp->next;
}
cout<<"NULL\n";
}
void Delete(int a)
{
if (head == NULL)
{
cout<<"Nothing to delete!\n";
return;
}
//if head node to be deleted
if (head->data == a)
{
Node *temp = head;
head = head->next;
delete temp;
return;
}
//iterate to the node to be deleted
Node *prev = NULL, *nxt = NULL, *cur = head;
while (cur != NULL && cur->data != a)
{
prev = cur;
cur = cur->next;
//if last node to be deleted
if (cur->next == NULL && cur->data == a)
{
delete cur;
prev->next = NULL;
return;
}
//node not found in the list
if (cur->data != a)
{
cout<<"Node not in the list!\n";
return;
}
nxt = cur->next;
delete cur;
prev->next = nxt;
}
}
};
int main()
{
Node list;
list.AppendAtEnd(12);
list.AppendAtEnd(20);
//list.AppendAtEnd(30);
list.AppendAtEnd(40);
list.Print();
list.Delete(12);
//list.Delete(30);
list.Delete(400);
//list.Delete(20);
list.Print();
return 0;
}