-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeletelastll.cpp
More file actions
71 lines (57 loc) · 1.36 KB
/
deletelastll.cpp
File metadata and controls
71 lines (57 loc) · 1.36 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
#include <iostream>
#include <vector>
#include <cstdlib>
using namespace std;
class Node
{
public :
int data;
Node *next;
Node(int data1, Node *next1)
{
data = data1;
next = next1;
}
Node(int data1)
{
data = data1;
next = nullptr;
}
};
// Function to print the linked list
void printLL(Node *head)
{
while (head != NULL)
{
cout << head->data << " -> ";
head = head->next;
}
cout << "NULL" << endl;
}
// Function to delete the last node of the linked list
Node* deleteLast(Node* head) {
if (head == nullptr || head->next == nullptr) {
return nullptr ;
}
Node* temp = head;
while(temp->next->next != nullptr) {
temp = temp->next;
}
delete temp->next; // Delete the last node
temp->next = nullptr; // Set the second last node's next to nullptr
return head;
}
int main()
{
// Sample array and value for insertion
vector<int> arr = {12, 80, 51, 7};
// Creating a linked list with initial elements from the array
Node *head = new Node(arr[0]);
head->next = new Node(arr[1]);
head->next->next = new Node(arr[2]);
head->next->next->next = new Node(arr[3]);
head = deleteLast(head); // Deleting the last node
// Printing the linked list
printLL(head);
return 0;
}