-
Notifications
You must be signed in to change notification settings - Fork 214
/
singlylinkedlist.cpp
127 lines (124 loc) · 2.58 KB
/
singlylinkedlist.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
#include <iostream>
using namespace std;
class Node{
public:
Node *next;
int data;
Node(int data){
this->data = data;
this->next = NULL;
}
};
void search(Node* &head, int d){
if (head == NULL){
cout << "List is empty";
exit(0);
}
Node* temp=head;
while(temp!=NULL && temp->data!=d){
temp=temp->next;
}
if (temp==NULL){
cout << "Element not found";
}
else cout << "Element found";
}
void display(Node* &head){
if (head == NULL){
cout << "List is empty";
exit(0);
}
Node* temp=head;
while(temp!=NULL){
cout << temp->data << endl;
temp=temp->next;
}
}
void InsertBeg(Node* &head,int d){
Node* temp=new Node(d);
temp->next=head;
head=temp;
}
void InsertEnd(Node* &head, int d){
Node* temp=new Node(d);
if (head==NULL){
cout << "Empty List";
}
else {
Node* temp1=head;
while(temp1->next!=NULL){
temp1=temp1->next;
}
temp1->next=temp;
}
}
void InsertVal(Node* &head,int d, int n){
Node* temp=new Node(d);
if (head==NULL){
cout << "Empty List";
}
else {
Node* temp1=head;
while(temp1!=NULL && temp1->data!=n){
temp1=temp1->next;
}
if (temp1==NULL){
cout << "Value not present";
}
else {
if (temp1->next==NULL){
temp1->next=temp;
temp->next=NULL;
}
else {
temp->next=temp1->next;
temp1->next=temp;
}
}
}
}
void DeleteBeg(Node* &head){
Node* temp=head;
if (head==NULL){
cout << "Empty list";
}
else {
head=head->next;
}
}
void DeleteEnd(Node *&head){
if (head==NULL){
cout << "Empty list";
}
else {
Node* temp=head;
while(temp->next->next!=NULL ){
temp=temp->next;
}
temp->next=NULL;
}
}
void DeleteSpec(Node *&head, int n){
Node* temp=head;
Node* prev=NULL;
if (temp!=NULL && temp->data==n){
head=head->next;
}
else {
while(temp!=NULL && temp->data!=n){
prev=temp;
temp=temp->next;
}
if(temp==NULL) cout << "Node not found";
prev->next=temp->next;
}
}
int main(){
Node n1(10),n2(20),n3(50);
n1.next=&n2;
n2.next=&n3;
Node *head =&n1;
display(head);
DeleteSpec(head,20);
display(head);
}