forked from Midway91/HactoberFest2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SinglyLinkedList.cpp
109 lines (88 loc) · 1.97 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
#include<iostream>
using namespace std;
class Node{
public:
int data;
Node* next;
Node(int data){
this->data = data;
this->next = NULL;
}
~Node(){
int value = this->data;
if(this->next != NULL){
delete next;
this->next = NULL;
}cout << "Memory is Free" << endl;
}
};
void InsertAtHead(Node* &head , int d){
Node* temp = new Node(d);
temp-> next = head;
head = temp;
}
void InsertatTail(Node* &tail,int d ){
Node* temp = new Node(d);
tail->next = temp;
tail = tail->next;
}
void DeleteAt(int position , Node* &head){
if( position == 1){
Node* temp = head;
head=head->next;
temp->next = NULL;
delete temp;
}
else{
Node* curr = head;
Node* prev = NULL;
int cnt = 1;
while(cnt < position){
prev = curr;
curr = curr->next;
cnt++;
}
prev->next = curr->next;
curr->next =NULL;
delete curr;
}
}
void print(Node* &head) {
Node* temp = head;
while (temp != NULL) {
cout << temp->data << endl;
temp = temp->next;
}
cout << endl;
}
void insertatMid(Node* &head, int postioin , int d){
Node* app = new Node(d);
Node* temp = head;
if(postioin == 1){
InsertAtHead(head,d);
return;
}
int cnt = 1;
while(cnt < postioin-1){
temp = temp->next;
cnt++;
}
app->next = temp->next;
temp->next = app;
}
int main(){
Node* node1 = new Node(11);
//cout << node1->data <<endl;
//cout << node1->next <<endl;
Node* head = node1;
Node* temp = node1;
InsertAtHead(head,9);
InsertAtHead(head,5);
InsertAtHead(head,3);
//print(head);
insertatMid(head,1,7);
print(head);
DeleteAt(1,head);
print(head);
return 0 ;
}