-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsingle_linked_list_insertion.cpp
102 lines (97 loc) · 1.69 KB
/
single_linked_list_insertion.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
#include<iostream>
using namespace std;
//writing structure
struct Node
{
int data;
Node* next;
};
//inserting data at beginning of the list
void insert_Begin(Node** head,int val)
{
Node* newnode=new Node();
newnode->data=val;
newnode->next=*head;
//set head to newnode
*head=newnode;
}
//insertion in after the given node where pointer to intermediate node is given
void insert_Mid(Node* head, Node* mid, int val)
{
if(head==NULL)
{
cout<<"No intermediate node! cant insert";
return;
}
Node* newnode=new Node();
newnode->data=val;
newnode->next=mid->next;
mid->next=newnode;
}
//insert data at the end
void insert_End(Node** head,int val)
{
Node* newnode=new Node();
newnode->data=val;
newnode->next=NULL;
if(*head==NULL)
{
*head=newnode;
return;
}
Node* tmp=*head;
while(tmp->next!=NULL)
{
tmp=tmp->next;
}
tmp->next=newnode;
}
//traverse the list
void traverse(Node* head)
{
while(head!=NULL)
{
cout<<head->data<<endl;
head=head->next;
}
}
void delete_Begin(Node** head)
{
//delete a node from the beginning
//just set head to next node of head
Node* tmp;
tmp=(*head)->next;
*head=tmp;
}
void delete_End(Node* head)
{
//delete a node from the end
//just set next of second last node to NULL
while(head->next->next!=NULL)
{
head=head->next;
}
head->next=NULL;
}
int main()
{
Node* head=NULL;
insert_Begin(&head,4);
insert_Begin(&head,11);
insert_End(&head,1);
Node* tmp=head;
while(tmp->data!=4)
{
tmp=tmp->next;
}
insert_Mid(head,tmp,55);
insert_Mid(head,tmp,12);
traverse(head);
cout<<"Deleting nodes from beginning"<<endl;
delete_Begin(&head);
traverse(head);
cout<<"Deleting nodes from End"<<endl;
delete_End(head);
traverse(head);
return 0;
}