19. 删除链表的倒数第N个节点
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
进阶:你能尝试使用一趟扫描实现吗?
我们先不管进阶的解法,来看一下快慢指针找链表长度,然后删除节点的解法:
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(!head) return head;
ListNode* hair=new ListNode(-1);
hair->next=head;
ListNode* fast=head;
ListNode* slow=head;
int len=1;
while(fast && fast->next)
{
slow=slow->next;
fast=fast->next->next;
len+=2;
}
if(fast) len++;
if(len==1 && n>=1) return NULL;
int move=len-n-1;
slow=hair;
while(move)
{
slow=slow->next;
--move;
}
slow->next=slow->next->next;
head=hair->next;
delete hair;
return head;
}
};
代码运行效果:
官方给的思路中还提到了一种使用栈数据结构的方法,比较巧妙。下面我们考虑使用一次遍历对倒数N节点进行删除,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: ListNode, n: int) -> ListNode:
if not head:
return
hair=ListNode(-1,head)
first=hair
second=hair
while(n):
second=second.next
n-=1
while(second.next):
first=first.next
second=second.next
first.next=first.next.next
return hair.next
运行效果:
这个思路是用两个指针分别储存最后节点和删除节点的上一个节点。
来源:力扣(LeetCode)链接