Problem
Given a linked list, remove the n-th node from the end of list and return its head.
Note:
Given n will always be valid.
Examples:
Input:1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Solutions
第一種方法是兩次遍歷,第一次計算出一共多少個節(jié)點,然后算出應(yīng)該向后移動多少次,
找到那個節(jié)點, 刪掉
- 第二種方法是使用雙指針一次遍歷, 兩個指針初始化為head,
后一個指針先跑n步, 然后當(dāng)后一個指針到達最后一個位置時,
前一個指針是倒數(shù)第n+1個, 刪掉第n個位置就可以
C++ Codes
雙指針
/**
* 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* p = head;
ListNode* pre=head;
for(n;n>=1;n--) p=p->next;
if(p==NULL)return head->next;
while(p->next!=NULL){
p=p->next;
pre=pre->next;
}
pre->next=pre->next->next;
return head;
}
};
Python Codes
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
if not head:return
dummy = ListNode(0)
dummy.next = head
fast = dummy
while n:
fast = fast.next
n -= 1
slow = dummy
while fast and fast.next:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return dummy.next
總結(jié)
- 雙指針另一個用法: 鏈表固定相差n個位置移動, 查找節(jié)點