-
Notifications
You must be signed in to change notification settings - Fork 30
/
linkedlist(insertion).cpp
103 lines (83 loc) · 1.57 KB
/
linkedlist(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
100
101
#include<iostream>
#include<stdlib.h>
using namespace std;
struct Node{
int data;
struct Node *next;
};
struct Node *head=NULL;
void insertAtBeginning(int data)
{
struct Node *new_node=(struct Node*)malloc(sizeof(struct Node));
new_node->data=data;
new_node->next=head;
head=new_node;
}
void insertAfter(int nodeafter,int data)
{
struct Node *temp;
temp=head;
if (head==NULL){
cout<<"list can't be inserted"<<endl;
}
else
{
while(temp->data!=nodeafter){
temp=temp->next;
if(temp==NULL){
cout<<"list can't be inserted"<<endl;
return;
}
}
struct Node *new_node=(struct Node*)malloc(sizeof(struct Node));
new_node->data=data;
new_node->next=temp->next;
temp->next=new_node;
}
}
void insertAtEnd(int data)
{
struct Node *temp;
temp=head;
struct Node *new_node=(struct Node*)malloc(sizeof(struct Node));
new_node->data=data;
new_node->next=NULL;
if(head==NULL)
{
head=new_node;
}
else{
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=new_node;
}
}
void printList(){
struct Node*ptr;
ptr=head;
while(ptr!=NULL){
cout<<ptr->data<<" ";
ptr=ptr->next;
}
cout<<endl;
}
int main() {
insertAtBeginning(1);
cout<<"After Inserting at Beginning: ";
printList();
insertAtBeginning(7);
cout<<"After Inserting at Beginning: ";
printList();
insertAtEnd(14);
cout<<"After Inserting at End: ";
printList();
insertAfter(7, 15);
cout<<"After Inserting after node 7: ";
printList();
insertAfter(1, 20);
cout<<"After Inserting after node 1: ";
printList();
return 0;
}