LeetCode19-刪除鏈表的倒數第N個節點
最近全國疫情嚴重,待在家裏沒事幹,馬上又要準備春招了,最近刷刷題,記錄一下!再說一句,武漢加油,大家出門記得戴口罩!
1、題目
給定一個鏈表,刪除鏈表的倒數第 n 個節點,並且返回鏈表的頭結點。
示例:
給定一個鏈表: 1->2->3->4->5, 和 n = 2.
當刪除了倒數第二個節點後,鏈表變爲 1->2->3->5.
說明:
給定的 n 保證是有效的。
進階:
你能嘗試使用一趟掃描實現嗎?
2、思路
使用雙指針解法,定義兩個指針:first和second,
第一個指針(first)先從鏈表的開頭向前移動 n步,
然後first和second同時向後移動,我們通過同時移動兩個指針向前來保持這個恆定的間隔,直到第一個指針到達最後一個結點。
Tips:定義一個虛擬頭結點,因爲原來的頭結點可能被刪除,引入虛擬頭結點後可以處理頭結點被刪除的情況,代碼中少一些判斷。如圖所示。
3、代碼
c++
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
//定義虛擬頭結點,指向head
auto dummy=new ListNode(-1);
dummy->next=head;
//定義兩個指針
auto first=dummy,second=dummy;
//first指針先走n步
while(n--) first=first->next;
//first和second指針同時走,直到first走到終止爲止
while(first->next)
{
first=first->next;
second=second->next;
}
second->next=second->next->next;
return dummy->next;
}
};
Java
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
//定義虛擬頭結點,指向head
ListNode dummy=new ListNode(-1);
dummy.next=head;
//定義兩個指針
ListNode first=dummy,second=dummy;
//first指針先走n步
for (int i = 1; i <= n; i++) {
first = first.next;
}
//first和second指針同時走,直到first走到終止爲止
while(first.next!=null)
{
first=first.next;
second=second.next;
}
second.next=second.next.next;
return dummy.next;
}
}