-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsinglyLinkedList.cpp
More file actions
128 lines (108 loc) · 2.68 KB
/
Copy pathsinglyLinkedList.cpp
File metadata and controls
128 lines (108 loc) · 2.68 KB
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
#include<iostream>
using namespace std;
class Node{
public:
int data;
Node* next;
Node(int val){
data = val;
next = NULL;
}
};
void insertAtHead(Node* &head,int val){
Node* new_node = new Node(val);
new_node->next = head;
head=new_node;
}
void insertAtTail(Node* &head, int val){
Node* new_node = new Node(val);
if(head == NULL){
head = new_node;
return;
}
Node* temp = head;
while(temp->next!=NULL){
temp = temp->next;
}
temp->next = new_node;
new_node->next = NULL;
}
void insertAtPosition(Node* &head, int pos, int val) {
if (pos == 1) {
insertAtHead(head, val);
return;
}
Node* temp = head;
int curr_pos = 0;
while (curr_pos < pos - 1 && temp != NULL) {
temp = temp->next;
curr_pos++;
}
if (temp == NULL) {
cout << "Position out of bounds. Cannot insert " << val << " at position " << pos << "." << endl;
return; // Exit the function safely
}
Node* new_node = new Node(val);
new_node->next = temp->next;
temp->next = new_node;
}
void deleteAtHead(Node* &head){
if(head == NULL) return;
Node* del= head;
head = head->next;
free(del);
}
void deleteAtTail(Node* &head){
if (head == NULL) return;
Node* secondlast = head;
while(secondlast->next->next != NULL){
secondlast = secondlast->next;
}
Node* del = secondlast->next;
secondlast->next = NULL;
free(del);
}
void deleteAtPosition(Node* &head, int pos){
if (head == NULL) return;
if (pos == 1){
deleteAtHead(head);
return;
}
Node* temp = head;
int curr_pos =0;
while (curr_pos < pos - 1 && temp != NULL){
temp = temp-> next;
curr_pos++;
}
if (temp == NULL || temp->next == NULL){
cout<<"position out of bounds"<<endl;
return;
}
Node* del = temp->next;
temp->next = del->next;
free(del);
}
void display(Node* head){
Node* temp = head;
while(temp != NULL){
cout << temp ->data << "-> ";
temp=temp->next;
}
cout<<"NULL"<<endl;
}
int main(){
Node* head = NULL;
Node node(0);
insertAtHead(head, 10);
insertAtHead(head, 20);
insertAtHead(head, 30);
insertAtTail(head, 40);
insertAtPosition(head, 2, 25);
deleteAtHead(head);
deleteAtTail(head);
deleteAtPosition(head,2);
display(head);
insertAtHead(head,50);
display(head);
return 0;
}