#include <iostream> struct Node { int data; Node* next; }; Node* deleteAtEnd(Node* head) { if (!head) return nullptr; if (!head->next) { delete head; return nullptr; } Node* temp = head; while (temp->next && temp->next->next) { temp = temp->next; } delete temp->next; temp->next = nullptr; return head; } void printList(Node* head) { while (head) { std::cout << head->data << " -> "; head = head->next; } std::cout << "null" << std::endl; } int main() { Node* head = new Node{1, new Node{2, new Node{3, nullptr}}}; head = deleteAtEnd(head); printList(head); return 0; }
The function deletes the last node (3) from the list. The remaining nodes are 1 and 2, so the printed list is 1 -> 2 -> null.
#include <iostream> struct Node { int data; Node* next; }; Node* deleteAtEnd(Node* head) { if (!head) return nullptr; if (!head->next) { delete head; return nullptr; } Node* temp = head; while (temp->next && temp->next->next) { temp = temp->next; } delete temp->next; temp->next = nullptr; return head; } void printList(Node* head) { while (head) { std::cout << head->data << " -> "; head = head->next; } std::cout << "null" << std::endl; } int main() { Node* head = new Node{10, nullptr}; head = deleteAtEnd(head); printList(head); return 0; }
Since the list has only one node, deleting the last node results in an empty list. So the printed output is null.
#include <iostream> struct Node { int data; Node* next; }; Node* deleteAtEnd(Node* head) { if (!head) return nullptr; Node* temp = head; while (temp->next) { temp = temp->next; } delete temp; temp = nullptr; return head; } void printList(Node* head) { while (head) { std::cout << head->data << " -> "; head = head->next; } std::cout << "null" << std::endl; } int main() { Node* head = new Node{1, new Node{2, new Node{3, nullptr}}}; head = deleteAtEnd(head); printList(head); return 0; }
The code deletes the last node but does not update the previous node's next pointer to nullptr. Later, printList tries to access the deleted node causing a segmentation fault.
After deleting the last node, the previous node's next pointer must be set to nullptr to avoid pointing to freed memory, which would cause undefined behavior if accessed.
#include <iostream> struct Node { int data; Node* next; }; Node* deleteAtEnd(Node* head) { if (!head) return nullptr; if (!head->next) { delete head; return nullptr; } Node* temp = head; while (temp->next && temp->next->next) { temp = temp->next; } delete temp->next; temp->next = nullptr; return head; } void printList(Node* head) { while (head) { std::cout << head->data << " -> "; head = head->next; } std::cout << "null" << std::endl; } int main() { Node* head = new Node{5, new Node{10, new Node{15, new Node{20, nullptr}}}}; head = deleteAtEnd(head); head = deleteAtEnd(head); head = deleteAtEnd(head); printList(head); return 0; }
Deleting last node thrice removes 20, then 15, then 10. The remaining list is just 5 -> null.
