-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedLists.cpp
More file actions
117 lines (102 loc) · 1.98 KB
/
LinkedLists.cpp
File metadata and controls
117 lines (102 loc) · 1.98 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
//Implemented linked list
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
//list node
struct node
{ int info;
struct node *next;
};
node *head=NULL,*tail=NULL;
//function to create a new node
node *getnode(int data)
{
node *newnode= new node();
newnode->info=data;
newnode->next=NULL;
if(head==NULL)
{
head=newnode;
tail=newnode;
}
else
{
tail->next=newnode;
tail=tail->next;
}
}
//function to Display the linked list
void display(struct node *start)
{
while(start!=NULL)
{
cout<<start->info<<" ";
start=start->next;
}
cout<<"\n";
}
// function to delete first node
void delete_first()
{
node *tmp=new node();
tmp=head;
head=head->next;
delete tmp;
}
void delete_last(struct node *ptr)
{
node *tmp=new node();
node *prev=new node();
while(ptr->next!=NULL)
{
prev=ptr;
ptr=ptr->next;
tmp=ptr;
}
delete tmp;
prev->next=NULL;
}
void delete_pos(int pos,struct node *ptr)
{
node *tmp=new node();
node *prev=new node();
for(int i=0;i<pos-1;i++)
{
prev=ptr;
ptr=ptr->next;
tmp=ptr;
}
prev->next=tmp->next;
delete tmp;
}
//driver code
main()
{
int size=0;
int p;
cout<<"enter no. of elements to be inserted=";
cin>>p;
for(int i=0;i<p;i++) //inserting elements in the list
{
int n;
cout<<"enter element to be inserted= ";
cin>>n;
getnode(n);
}
cout<< "\nThe List is : ";
display(head);
delete_first();
cout<<"\nList after deleting the first node :";
display(head);
delete_last(head);
cout<<"\n List after deleting the last node : ";
display(head);
cout<<"\nLet's delete an element at some position :";
cout<<"\nEnter pos: ";
int position;
cin>>position;
delete_pos(position,head);
cout<<"\nList after deleting the element : ";
display(head);
return 0;
}