简体   繁体   中英

Remove kth last element from a Singly Linked List in a single pass

I'm practising Python and I couldn't think of any solution to this problem. The problem is to remove kth last element from a singly linked list in just one pass and constant space. I can only think of a solution that requires 2 passes. Also, in the question, the size of the list was not mentioned, so I'm assuming the size is known apriori. Can anyone show me a way to do it in a single pass, please?

Cache the pointer/location of the item before the item to be removed, in a temp variable as you go along.

So there would be one loop, iterating to the end. There would be a statement that caches (ik-1)th element in temp.

When this loop ends, temp would have the location of the item to be removed.

Hope this helps.

If the size is known then you want to remove the s - kth element.

If it's not the case then I would use two runners, one is k indices ahead of the second one. When your first runner reaches the end of your list, your second runner is exactly pointing to the kth last element.

From GeeksforGeeks

Method 2 (Use two pointers)

Maintain two pointers – reference pointer and main pointer. Initialize both reference and main pointers to head. First move reference pointer to n nodes from head. Now move both pointers one by one until reference pointer reaches end. Now main pointer will point to nth node from the end. Return main pointer.

An implementation in python is available.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM