سوال ۶۳ کنکور ارشد علوم کامپیوتر ۱۴۰۵
فرض کنید P یک لیست تکپیوندی باشد و همچنین Q اشارهگری به گرهی میانی X در لیست باشد. پیچیدگی زمانی بهترین الگوریتم شناخته شده برای حذف گره Q از لیست چیست؟
پاسخ صحیح: گزینهٔ B —
Setting up the problem
We have a singly-linked list with head pointer and a pointer to the middle node . We must delete the node object that points to.
Why the predecessor is required
To unlink a node from a singly-linked list you have to redirect the predecessor's next pointer past it:
But a singly-linked node stores no back-pointer, so the only way to find 's predecessor is to walk from the head until you reach the node whose next equals . Since is the middle node this scan touches about nodes, i.e. , and no known method beats it — so the cost is .
The famous trick does not solve this task
There is a well-known constant-time trick for a non-tail node:
Q.data = Q.next.data
Q.next = Q.next.next // frees the successor node
This runs in , but look at which node it removes: it deletes 's successor, while node survives holding a copied value. The problem asks to delete node itself, so the trick answers a different question. To remove the actual node you are forced back to locating its predecessor, which is .
Hence the best known algorithm is — option 2.
Pitfall: The copy-and-delete trick is only for deleting the value at (and only when is not the tail). It does not remove the node object ; deleting that specific node needs its predecessor, which is in a singly-linked list.