سوال ۶۳ کنکور ارشد علوم کامپیوتر ۱۴۰۴
فرض کنید یک لیست پیوندی یکطرفه داریم. میخواهیم گره دوم از انتها یعنی گره ماقبل آخر را حذف کنیم. بهترین روش برای انجام این کار چیست؟
پاسخ صحیح: گزینهٔ D — استفاده از دو اشارهگر که یکی از دو گره جلوتر از دیگری است.
In a singly linked list, deleting a node requires a pointer to its predecessor, because we can only follow links forward. To remove the second-from-last node we must end up holding a pointer to the third-from-last node (so we can splice past the node being deleted).
The classic single-pass technique uses two pointers separated by a fixed gap. To delete the node that is from the end, advance a lead pointer nodes ahead of a trail pointer, then move both together one step at a time. When the lead pointer reaches the last node (or the end), the trail pointer is exactly positioned at the predecessor of the target. Here the target is the nd from the end, so the trail pointer should sit at the rd from the end, i.e. the lead is two nodes ahead of the trail.
... -> [trail] -> [target = 2nd-from-end] -> [last]
^ lead reaches here
trail.next = trail.next.next // splice out the target
This runs in a single traversal, time and extra space, with no counting of the total length needed.
Why the others are worse:
| Option | Verdict |
|---|---|
| 1. Convert to an array | Needs extra space and an extra pass to rebuild/relink — wasteful. |
| 2. Walk to the end and count | A counting pass tells you the length but you still need a second pass to reach the predecessor. |
| 3. One pointer + counter to the target | Knowing the position from the end still requires knowing first (another pass), or it lands you on the target rather than its predecessor. |
| 4. Two pointers with a fixed gap | One pass, space, lands directly on the predecessor. Best. |
So the best method is option 4.
Exam trick: For any "-th node from the end" operation on a singly linked list, the standard optimal answer is the two-pointer (fast/slow) technique with the two pointers kept a fixed distance apart — one traversal, constant extra memory.