To find the last node of a singly linked list, we must keep moving until the link (next pointer) becomes NULL. This ensures we stop exactly at the last node.
// Structure of node
struct Node {
int data;
struct Node* link;
};
// Function to get last node
struct Node* getLastNode(struct Node* head) {
struct Node* temp = head;
// Traverse until last node
while (temp -> link != NULL) {
temp = temp -> link;
}
return temp; // Now temp points to last node
}
Explanation:
temp with head.temp = temp → link while temp → link != NULL.temp is pointing to the last node.Correct Code Logic:
while (temp → link != NULL) temp = temp → link;
Online Test Series, Information About Examination,
Syllabus, Notification
and More.
Online Test Series, Information About Examination,
Syllabus, Notification
and More.