-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinked list delete node from beginning or end.cpp
109 lines (93 loc) · 1.37 KB
/
Linked list delete node from beginning or end.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
102
103
104
105
106
107
108
109
#include <iostream>
using namespace std;
//Creating Node Structure
struct Node{
int data;
Node *link;
};
//creating head pointer and equating to NULL
Node *head=NULL;
//Function to delete node at the beginning
void deleteBeg(){
//if list is empty.
if(head==NULL)
cout<<"LIST IS EMPTY\n";
else
{
Node *ptr=head;
head=head->link;
free(ptr);
}
}
//Function to delete node at the end
void deleteEnd()
{
Node *ptr;
//if list is empty.
if(head==NULL)
cout<<"EMPTY LIST\n";
//if list has only one node.
if(head->link==NULL)
{
ptr=head;
head=NULL;
free(ptr);
}
//Traversing the list.
else
{ Node *prev;
ptr=head;
while(ptr->link!=NULL)
{
prev=ptr;
ptr=ptr->link;
}
prev->link=NULL;
free(ptr);
}
}
//Function to insert at the end of linked list
void insertEnd (int d)
{
Node *ptr = new Node();
ptr->data=d;
ptr->link=NULL;
if(head==NULL)
head=ptr;
else
{
Node *temp = head;
while(temp->link != NULL)
{
temp=temp->link;
}
temp->link=ptr;
}
}
// function to display Linked list
void displayList(){
Node *ptr=head;
if(head==NULL)
cout<<"LIST IS EMPTY\n";
while(ptr!=NULL)
{
cout<<ptr->data<<" ";
ptr=ptr->link;
}
cout<<"\n";
}
//Main Function
int main()
{
insertEnd(1);
insertEnd(2);
insertEnd(3);
insertEnd(4);
insertEnd(5);
displayList();
deleteBeg();
displayList();
deleteEnd();
displayList();
return 0;
}