【題目描述】
Given a linked list, remove the nth node from the end of list and return its head.
【注】The minimum number of nodes in list is?n.
給定一個鏈表,刪除鏈表中倒數第n個節點,返回鏈表的頭節點。
【注】鏈表中的節點個數大于等于n
【題目鏈接】
www.lintcode.com/en/problem/remove-nth-node-from-end-of-list/
【題目解析】
此題可用雙指針來解決。
首先讓faster從起始點往后跑n步。再讓slower和faster一起跑,直到faster==null時候,slower所指向的node就是需要刪除的節點。
注意,一般鏈表刪除節點時候,需要維護一個prev指針,指向需要刪除節點的上一個節點。
為了方便起見,當讓slower和faster同時一起跑時,就不讓 faster跑到null了,讓他停在上一步,faster.next==null時候,這樣slower就正好指向要刪除節點的上一個節點,充當了prev指針。這樣一來,就很容易做刪除操作了。
slower.next = slower.next.next(類似于prev.next = prev.next.next)。
同時,這里還要注意對刪除頭結點的單獨處理,要刪除頭結點時,沒辦法維護prev節點,所以當發現要刪除的是頭結點時,直接讓head = head.next并return head即可。
【參考答案】
www.jiuzhang.com/solutions/remove-nth-node-from-end-of-list/