forked from dharmanshu1921/Website-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsingleLL.cpp
134 lines (107 loc) · 2.4 KB
/
singleLL.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
#include<bits/stdc++.h>
using namespace std;
class Node{
public:
int data;
Node* next;
//constructor
Node(int data){
this->data = data;
this->next = NULL;
}
//destructor
~Node(){
int value = this->data;
if(this->next != NULL){
delete next;
this->next = NULL;
}
cout<<"Deleted value is : "<< value << endl;
}
};
void insertAtHead(Node* &head , int data){ //head is taken as reference
//new Node created
Node* temp = new Node(data);
temp->next = head;
head = temp;
}
//insert a new node at last
//we make use of tail pointer that always shows the last node in given LL
void insertAtTail(Node* &tail , int data){
//new Node created
Node* temp = new Node(data);
tail->next = temp;
tail = temp;
}
void insertAtPosition(Node* &head , Node* &tail , int data , int pos){
if(pos == 1)
{
insertAtHead(head , data);
return;
}
//new Node created
Node* temp = new Node(data);
Node* p = head;
int count = 1;
while(count < pos-1){
p = p->next;
count++;
}
if(p->next == NULL){
insertAtTail(tail , data);
return ;
}
temp->next = p->next;
p->next = temp;
}
//delete start node
void deleteHead(Node* &head){
Node* temp = head;
head = head -> next;
temp->next = NULL;
delete temp;
}
void deleteAtPosition(Node* &head , Node* &tail , int pos){
if(pos == 1){
deleteHead(head);
return ;
}
else{
Node* curr = head;
Node* prev = NULL;
int count = 1;
while(count < pos){
prev = curr;
curr = curr->next;
count++;
}
prev->next = curr->next;
if(curr->next == NULL){
tail = prev;
}
curr->next = NULL;
delete curr;
}
}
void display(Node* &head){
Node* p = head;
while(p != NULL){
cout<< p->data << " ";
p = p->next;
}
cout<<endl;
}
int main(){
Node* head = new Node(10); //new Node created and passed data
Node* tail = head;
insertAtHead(head , 5);
display(head);
insertAtTail(tail,15);
display(head);
insertAtPosition(head , tail , 12 , 3);
display(head);
deleteAtPosition(head , tail , 4);
display(head);
cout<<"tail data : "<<tail->data;
return 0;
}