You are given pointers to first and last nodes of a singly linked list, which…
2024
You are given pointers to first and last nodes of a singly linked list, which of the following operations are dependent on the length of the linked list?
- A.
Delete the first element
- B.
Insert a new element as a first element
- C.
Delete the last element of the list
- D.
Add a new element at the end of the list
Attempted by 32 students.
Show answer & explanation
Correct answer: C
Concept: In a singly linked list, each node stores only a pointer to its NEXT node -- there is no pointer back to a node's predecessor. Any operation that needs to locate the node BEFORE a given node must walk the list from the head, taking time proportional to the list's length. An operation that only touches the head node or the tail node directly, using the given head/tail pointers, completes in constant time, independent of length.
Removing the first node: the head pointer is moved directly to the second node and the old head is freed -- no traversal needed.
Inserting a node as the new first node: the new node's next is set to the current head, then the head pointer is updated to the new node -- a direct pointer update.
Removing the last node: the node before it must become the new tail. Since nodes only link forward, the only way to find that predecessor is to walk from the head, node by node, until reaching the node whose next points at the current tail; only after locating it can its next be set to null (or the sentinel) and tail be updated -- only then is the old last node's memory freed.
Adding a node at the end: the tail pointer's next is set to the new node, then tail is updated to the new node -- a direct pointer update.
Cross-check: contrast this with a doubly linked list, where each node also stores a pointer to its predecessor. There, removing the last node would also be a direct pointer update, since the tail's predecessor pointer gives the new tail immediately, with no walk at all. This confirms the length-dependence found here comes specifically from the singly-linked, forward-only structure -- not from deletion in general.
Result: among the four operations, only removing the last node needs a walk whose length grows with the size of the list; the other three are all direct, constant-time pointer updates using the given head/tail pointers.