-
Notifications
You must be signed in to change notification settings - Fork 0
/
Source.cpp
129 lines (126 loc) · 2.06 KB
/
Source.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
#include<iostream>
using namespace std;
class node
{
public:
int data;
node* next;
node* head;
node(int val)
{
data = val;
next = NULL;
}
};
void InsertAtTail(node*& head, int val) //Funtion for Insert at Last
{
node* n = new node(val);
if (head == NULL)
{
head = n;
return;
}
node* temp = head;
while (temp->next != NULL)
{
temp = temp->next;
}
temp->next = n;
}
void display(node* head)
{
node* temp = head;
while (temp->next != NULL)
{
cout << temp->data << " " << "-->" << " ";
temp = temp->next;
}
cout << "NULL" << endl;
}
void InsertAtHead(node*& head, int val) //Function for Insertion at First
{
node* n = new node(val);
if (head == NULL)
{
head = n;
head->next = NULL;
}
else
{
node* temp;
temp = head;
head = n;
head->next = temp;
}
}
bool search(node* head, int key) //Search In Linked List
{
node* temp = head;
while (temp != NULL)
{
if (temp->data == key)
{
return true;
}
temp = temp->next;
}
return false;
}
void DeleteFirstNode(node*& head)
{
if (head == NULL)
{
return;
}
node* temp = head;
head = temp->next;
delete temp; //does not matter
}
void Deletion(node*&head, int val) //Deletion of nth Node
{
if (head == NULL)
{
return;
}
else if (head->next == NULL)
{
node* temp = head;
head = NULL;
return;
}
node* temp = head;
while (temp->next->data != val)
{
temp = temp->next;
}
temp->next = temp->next->next;
/*node* todelete = temp->next;
temp->next=temp->next->next;
delete todelete; */
//It works even if these three lines does not mentioned in code
}
int main()
{
node* head = NULL;
InsertAtTail(head, 1);
InsertAtTail(head, 2);
InsertAtTail(head, 3);
InsertAtTail(head, 4);
display(head);
InsertAtHead(head, 10);
InsertAtHead(head, 20);
InsertAtHead(head, 30);
display(head);
cout << search(head, 10) << endl;
cout << search(head, 6) << endl;
Deletion(head, 10);
display(head);
DeleteFirstNode(head);
display(head);
DeleteFirstNode(head);
DeleteFirstNode(head);
DeleteFirstNode(head);
DeleteFirstNode(head);
display(head);
return 0;
}