-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinked_List.cpp
138 lines (117 loc) · 2.76 KB
/
Linked_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
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
130
131
132
133
134
135
136
137
138
//INCOMPLETE
#include<iostream>
using namespace std;
class Node
{
public:
int m_data{};
Node* m_next{};
Node(int data = 0):m_data{data}
{
}
};
void appendAtTheEnd(Node** headptr, int newData)
{
Node* newNode = new Node(newData);
Node* temp{};
if(*headptr == NULL)
{
*headptr = newNode;
newNode->m_next = NULL;
return;
}
for(temp = *headptr; temp -> m_next != NULL; temp = temp -> m_next)
{
}
temp -> m_next = newNode;
newNode ->m_next = NULL;
}
void appendAtTheBeginning(Node** headptr, int newData)
{
Node* newNode = new Node(newData);
Node* temp = *headptr;
*headptr = newNode;
newNode ->m_next = temp;
}
void appendAfterNode(Node** headptr, int newData, int dataAfterWhichToAppend)
{
Node* newNode = new Node(newData);
Node* temp = *headptr;
for(;temp != NULL; temp = temp->m_next)
{
if(temp ->m_data == dataAfterWhichToAppend)
{
break;
}
}
if(temp != NULL)
{
Node* tempNew = temp -> m_next;
temp -> m_next = newNode;
newNode -> m_next = tempNew;
}
else
{
cout << "Element After which to be Appended Not Found\n";
}
}
void deleteNode(Node** headptr, int dataToBeDeleted)
{
Node* prev{};
prev = *headptr;
if(prev->m_data == dataToBeDeleted)
{
Node* temp = *headptr;
*headptr = prev->m_next;
temp->m_next = NULL;
return;
}
for(prev = *headptr; prev -> m_next != NULL && prev -> m_next ->m_data != dataToBeDeleted; prev = prev -> m_next)
{
}
Node* temp = prev -> m_next;
prev -> m_next = temp -> m_next;
temp -> m_next = NULL;
}
void updateNode(Node** headptr, int dataToBeUpdated, int newData)
{
Node* temp = *headptr;
while(temp != NULL)
{
if(temp ->m_data == dataToBeUpdated)
{
temp ->m_data = newData;
break;
}
temp = temp->m_next;
}
if(temp == NULL)
{
cout << "Data to be updated Not Found\n";
}
}
void printLinkedList(Node** headptr)
{
Node* temp = *headptr;
cout << "Head\n'\n'--";
for(;temp != NULL; temp = temp -> m_next)
{
cout << temp ->m_data << " --> ";
}
cout << "NULL\n\n";
}
int main()
{
Node* head{};
appendAtTheEnd(&head, 10);
printLinkedList(&head);
appendAtTheBeginning(&head, 20);
printLinkedList(&head);
appendAfterNode(&head, 30, 20);
printLinkedList(&head);
updateNode(&head, 30, 40);
printLinkedList(&head);
deleteNode(&head, 10);
printLinkedList(&head);
return 0;
}