-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathsingly_linked_list.cpp
150 lines (119 loc) · 2.55 KB
/
singly_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
139
140
141
142
143
144
145
146
147
148
149
150
#include<iostream>
using namespace std;
class node{
public:
int data;
node* next;
//constructor
node(int data){
this -> data=data;
this -> next=NULL;
}
};
//insert a node at head
void InsertAtHead(node* &head, int data){
node* temp=new node(data);
temp -> next = head;
head = temp;
}
//insert a node at tail
void InsertAtTail(node * &tail, int data){
node* temp = new node(data);
tail -> next=temp;
tail=tail->next;
}
//insert node at position
void InsertAtPosition(node* &tail, node* &head, int position, int d){
//insert at position 1
if(position==1){
InsertAtHead(head,d);
return;
}
node* temp=head;
int count=1;
while(count < position-1){
temp=temp->next;
count++;
}
//insert at position last
if(temp->next == NULL){
InsertAtTail(tail,d);
return;
}
//createing a node for d
node* newnode = new node(d);
newnode->next=temp->next;
temp->next=newnode;
}
//delete a node
void deleteNode(int position, node* &head){
//deleting first node
if(position==1){
node* temp=head;
head=head->next;
//memory free first node
temp->next=NULL;
delete temp;
}
else{
//deleting an middle or last node
node* curr=head;
node* prev=NULL;
int count=1;
while(count < position){
prev=curr;
curr=curr->next;
count++;
}
prev->next=curr->next;
curr->next=NULL;
delete curr;
}
}
//reverse a ll
void reverseLinkedList(node* &head){
if(head==NULL || head->next==NULL){
return;
}
node* prev=NULL;
node* curr=head;
node* forward=NULL;
while(curr != NULL){
forward = curr -> next ;
curr->next=prev;
prev=curr;
curr=forward;
}
head=prev;
}
//traversing a linked list
void print(node* &head){
node* temp = head;
while(temp != NULL){
cout<<temp->data<<" ";
temp=temp->next;
}
cout<<endl;
}
int main(){
node* node1 = new node(5);
node* head=NULL;
node* tail=node1;
print(head);
InsertAtHead(head,10);
print(head);
InsertAtHead(head,15);
print(head);
InsertAtTail(tail,20);
print(head);
InsertAtTail(tail,25);
print(head);
// cout<<endl;
InsertAtPosition(tail,head,4,50);
print(head);
deleteNode(6,head);
print(head);
cout<<"head "<<head->data<<endl;
cout<<"tail "<<tail->data<<endl;
return 0;
}