-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathLinkedListOperations
More file actions
136 lines (124 loc) · 2.51 KB
/
LinkedListOperations
File metadata and controls
136 lines (124 loc) · 2.51 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
129
130
131
132
133
134
135
136
#include<bits/stdc++.h>
using namespace std;
struct node
{
int data;
struct node *next;
};
struct node *Create(int n)
{
struct node *head,*temp;
head=(struct node*)malloc(sizeof(struct node));
head->data=1;
head->next=NULL;
temp=head;
for(int i=2;i<=n;i++)
{
struct node* newnode=(struct node*)malloc(sizeof(struct node));
newnode->data=i;
newnode->next=NULL;
temp->next=newnode;
temp=newnode;
}
return head;
}
struct node *Insert(struct node *head,int val,int pos)
{
struct node *temp=head;
struct node *newnode=(struct node*)malloc(sizeof(struct node));
newnode->data=val;
if(pos==1)
{
newnode->next=head;
head=newnode;
}
else
{
int j=1;
while(j<pos-1)
{
temp=temp->next;
j++;
}
newnode->next=temp->next;
temp->next=newnode;
}
return head;
}
struct node *Delete(struct node *head,int pos)
{
struct node *temp=head,*delNode;
if(pos==1)
{
head=head->next;
free(temp);
}
else
{
int j=1;
while(j<pos-1)
{
temp=temp->next;
j++;
}
delNode=temp->next;
temp->next=temp->next->next;
free(delNode);
}
return head;
}
void printLL(struct node *head)
{
struct node *temp;
temp=head;
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp=temp->next;
}
cout<<endl;
}
int main()
{
struct node *head;
int n,value,pos;
//Number of Nodes In Linked List
cout<<"Enter The Number Of Nodes"<<endl;
cin>>n;
//Creating The Linked List
head=Create(n);
//Printing The Linked List
cout<<"Linked List:"<<endl;
printLL(head);
//Insertion In Linked List
cout<<"Enter Value To Be Inserted In Linked List"<<endl;
cin>>value;
cout<<"Enter Position"<<endl;
cin>>pos;
if(pos>n+1)
{
cout<<"Position Not Available"<<endl;
}
else
{
head=Insert(head,value,pos);
//Printing The Linked List
cout<<"Linked List:"<<endl;
printLL(head);
}
//Deletion In Linked List
cout<<"Enter The Postion For Deletion"<<endl;
cin>>pos;
if(pos<1 || pos>n)
{
cout<<"Position Not Available"<<endl;
}
else
{
head=Delete(head,pos);
//Printing The Linked List
cout<<"Linked List:"<<endl;
printLL(head);
}
return 0;
}