-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathdeletion_at_end_of_linked_list.cpp
More file actions
118 lines (104 loc) · 2.55 KB
/
deletion_at_end_of_linked_list.cpp
File metadata and controls
118 lines (104 loc) · 2.55 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
#include <iostream>
using namespace std;
struct node
{
int num;
node *nextptr;
}*stnode; //node constructed
void createList(int n);
void lastDelete();
void display();
int main()
{
int n,num,pos;
cout<<"Enter the number of nodes: ";
cin>>n;
createList(n);
cout<<"\nLinked list data: \n";
display();
lastDelete();
cout<<"\nLinked list after deletion: \n";
display();
return 0;
}
void createList(int n) //function to create linked list
{
struct node *frntNode, *tmp;
int num, i;
stnode = (struct node *)malloc(sizeof(struct node));
if(stnode == NULL)
{
cout<<" Memory can not be allocated";
}
else
{
cout<<"Enter the data for node 1: ";
cin>>num;
stnode-> num = num;
stnode-> nextptr = NULL; //Links the address field to NULL
tmp = stnode;
for(i=2; i<=n; i++)
{
frntNode = (struct node *)malloc(sizeof(struct node));
if(frntNode == NULL) //If frntnode is null no memory cannot be allotted
{
cout<<"Memory can not be allocated";
break;
}
else
{
cout<<"Enter the data for node "<<i<<": "; // Entering data in nodes.
cin>>num;
frntNode->num = num;
frntNode->nextptr = NULL;
tmp->nextptr = frntNode;
tmp = tmp->nextptr;
}
}
}
}
void lastDelete()//function to delete last node
{
struct node *delLast, *preNode;
if(stnode == NULL)
{
cout<<"List is empty";
}
else
{
delLast = stnode;
preNode = stnode;
while(toDelLast->nextptr != NULL)//Traversing till the last.
{
preNode = delLast;
delLast = delLast->nextptr;
}
if(delLast == stnode)
{
stnode = NULL;
}
else
{
preNode->nextptr = NULL;
}
free(delLast);//Deleting last node
}
}
void display() //function to print linked list
{
struct node *tmp;
if(stnode == NULL)
{
cout<<" No data found in the list";
}
else
{
tmp = stnode;
cout<<"Linked List: ";
while(tmp != NULL)
{
cout<<"\t"<<tmp->num;
tmp = tmp->nextptr;
}
}
}