题目
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list
思路1
首先计算链表的长度,再判断n是否表示的是第一个节点,若是,直接返回head.next,否则找到要删除的节点的前两个节点,最后删除目标节点
代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
now=head
num=1
while(now.next):
now=now.next
num+=1
if(num==n):
return head.next
now=head
for i in range(num-n-1):
now=now.next
now.next=now.next.next
return head
思路2
双指针,倒数第n个节点是指距离链表末尾的距离,所以定义一个快指针,先移动n个距离,在定义一个快指针,让快慢指针一起移动,需要注意的是当快指针移动到倒数第二个时停止,方便删除节点,此时慢指针所指的位置是目标节点的前一位,所以很简单就能删除节点。(记得判断n是否为第一个节点)
代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
slow=head
fast=head
while(n):
if fast.next:
fast=fast.next
n-=1
else:
return head.next
while(fast.next):
fast=fast.next
slow=slow.next
slow.next=slow.next.next
return head