-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdeletion in linkedlist.cpp
78 lines (77 loc) · 1.26 KB
/
deletion in linkedlist.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
#include<iostream>
#include<cstdlib>
using namespace std;
struct node{
int data;
node* next;
};
node* head=NULL;
void deletebeg(){
if(head==NULL){
cout<<"list is empty";
}
else{
node* ptr=head;
head=head->next;
free(ptr);
}
}
void deleteend(){
if(head==NULL)//no element
cout<<"empty list";
else if(head->next==NULL){//if only 1 element present
node* ptr=head;
head=NULL;
free(ptr);
}
else{
node* ptr=head;
node* prev;//creating a pointer to previous node, so that we can delete the last node
while(ptr->next!=NULL){
prev=ptr;
ptr=ptr->next;
}
prev->next=NULL;
free(ptr);
}
}
void insertbeg(int d){
node* ptr=new node();
ptr->data=d;
ptr->next=head;
head=ptr;
}
void insertend(int d){
node* ptr=new node();
ptr->data=d;
ptr->next=NULL;
if(head==NULL)
head=ptr;
else{
node* temp=head;
while(temp->next!=NULL){
temp=temp->next;
}
temp->next=ptr;
}
}
void display(){
node* temp=head;
while(temp!=NULL){
cout<<temp->data<<" ";
temp=temp->next;
}
}
int main(){
insertbeg(8);
insertbeg(7);
insertend(9);
insertend(10);
insertend(12);
display();
cout<<"\n";
deletebeg();
deleteend();
display();
return 0;
}