1. 删除链表的倒数第N个节点
19
题目:给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
输入:head = [1], n = 1
输出:[]
思路: 快慢指针法,通过fast-slow=n就能通过一次遍历就找到逆序n的位置(slow所指结点)。 快慢指针法可以用于对倒数第n个数操作类型
笔记: 注意:让fast先走和后面fast,slow一起走,要分开写在两个循环里,不然[1],1的情况就会陷入死循环。 因为[1],1时,slow是不需要动的,所以要在第二个while里重新判断一次(只写一个循环一定会有slow和fast一起走这两步),跳过这两句。
另:while(n–)判断时用的是n的值,然后再-1
while(fast->next != NULL ) {
for (; n != 0; n--) {
fast = fast->next;
}
fast = fast->next;
slow = slow->next;
}
C++:
class Solution {
public:
ListNode *removeNthFromEnd(ListNode *head, int n) {
ListNode *dummy = new ListNode(0);
dummy->next = head;
ListNode *fast = dummy;
ListNode *slow = dummy;
while(n-- && fast != NULL){
fast = fast->next;
}
fast = fast->next;
while(fast != NULL){
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next;
return dummy->next;
}
};
Python:
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
dummy = ListNode(next=head)
slow, fast = dummy, dummy
while(n != 0 and fast.next != None):
fast = fast.next
n -= 1
while(fast.next != None):
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return dummy.next
|