-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathLINKED_LIST_OPERATIONS.cpp
109 lines (94 loc) · 2.32 KB
/
LINKED_LIST_OPERATIONS.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
#include<bits/stdc++.h>
using namespace std;
class node{
public:
int val;
node* next;
};
node* newNode(int val){
node* new_node = new node();
new_node->val = val;
new_node->next = NULL;
return new_node;
}
void print_list(node* head){
while(head != NULL){
cout<<head->val<<" ";
head = head->next;
}
cout<<endl;
}
void insert_at_start(node** head, int val){
node* new_node = newNode(val);
new_node->next = *head;
*head = new_node;
}
void insert_after_node(node* ptr_node, int val){
node* new_node = newNode(val);
new_node->next = ptr_node->next;
ptr_node->next = new_node;
}
void insert_at_end(node** head, int val){
node* new_node = newNode(val);
if(*head == NULL){
*head = new_node;
return;
}
node* head_node = *head;
while(head_node->next != NULL){
head_node = head_node->next;
}
head_node->next = new_node;
}
void delete_from_list(node** head, int val){
node* head_node = *head;
node* prev_node;
if(head_node != NULL and head_node->val == val){
*head = head_node->next;
delete head_node;
return;
}
while(head_node != NULL and head_node->val != val){
prev_node = head_node;
head_node = head_node->next;
}
if(head_node != NULL){
prev_node->next = head_node->next;
delete head_node;
}
}
void delete_at_pos(node** head, int pos){
node* head_node = *head;
node* prev_node;
if(pos == 0){
if(head_node == NULL){
return;
}
*head = head_node->next;
delete head_node;
}else{
while(pos and head_node != NULL and head_node->next != NULL){
pos--;
prev_node = head_node;
head_node = head_node->next;
}
if(pos == 0){
prev_node->next = head_node->next;
delete head_node;
}
}
}
int main(){
node* linked_list = NULL;
insert_at_start(&linked_list, 3);
insert_at_start(&linked_list, 4);
insert_at_start(&linked_list, 5);
insert_after_node(linked_list->next, 10);
insert_at_end(&linked_list, 20);
print_list(linked_list);
delete_from_list(&linked_list, 20);
print_list(linked_list);
delete_at_pos(&linked_list, 3);
print_list(linked_list);
return 0;
}