Description
Given a linked list, remove the n-th node from the end of list and return its head.
Example:
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Follow up:
Could you do this in one pass?
分析
题目的意思是:移除链表中倒数第k个节点。
- 这道题利用快慢指针,首先快指针先移动k个节点,然后快慢指针一起移动,当块指针移动到末尾时,慢指针指向的节点的下一个节点就是要移除的节点。
- 这里利用了一个trick,就是在表头多加了一个节点,这样能避免头节点为空的情况,也能够在最后返回链表的头节点。
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* pre=new ListNode(-1);
pre->next=head;
ListNode* fast=pre;
while(n>0&&fast){
fast=fast->next;
n--;
}
if(n>0){
return NULL;
}
ListNode* slow=pre;
while(fast->next){
slow=slow->next;
fast=fast->next;
}
slow->next=slow->next->next;
return pre->next;
}
};
Python 代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
root_node=ListNode()
root_node.next=head
for i in range(n):
head=head.next
p=root_node.next
pre=root_node
while head:
pre=pre.next
p=p.next
head=head.next
pre.next=p.next
return root_node.next
第二个版本:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
# two pointers
dummpy = ListNode(-1)
dummpy.next = head
p = dummpy
for i in range(n):
p = p.next
pre = dummpy
while p and p.next:
p = p.next
pre = pre.next
pre.next = pre.next.next
return dummpy.next