LeetCode演算法題19:刪除連結串列的倒數第N個節點解析
阿新 • • 發佈:2019-01-03
給定一個連結串列,刪除連結串列的倒數第 n 個節點,並且返回連結串列的頭結點。
示例:
給定一個連結串列: 1->2->3->4->5, 和 n = 2.
當刪除了倒數第二個節點後,連結串列變為 1->2->3->5.
說明:
給定的 n 保證是有效的。
進階:
你能嘗試使用一趟掃描實現嗎?
直接搞進階,一趟實現,那麼既然是倒數第n個,那就可以設定兩個指標,前面的指標先遍歷n次,然後兩個指標再一起走,當第一個指標指向末尾時,那麼第二個指標就指向了倒數第n個。寫演算法時需要注意,如果是要刪除頭元素,那麼第一個指標最後指向了空。所以第一個指標第一次遍歷之後需要判斷一下,然後第二次遍歷時需要判斷的條件是第一指標的下一個是否為空,因為我們需要獲得的不是指向倒數第n個的指標,而是其上一個。
C++原始碼:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *first=head;
ListNode *second=head;
while(n--)
first = first->next;
if(first==NULL)
return head->next;
while(first->next!=NULL)
{
first = first->next;
second = second->next;
}
second->next = second->next->next;
return head;
}
};
python3原始碼:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
first = head
second = head
while n!=0:
first = first.next
n -= 1
if first==None:
return head.next
while first.next!=None:
first = first.next
second = second.next
second.next = second.next.next
return head