题目描述:
给你一个链表,删除链表的倒数第 n
个结点,并且返回链表的头结点。
进阶:你能尝试使用一趟扫描实现吗?
输入:head = [1,2,3,4,5], n = 2 输出:[1,2,3,5]
思路:
双指针
先让一个指针先走n步
之后两个指针一起走
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
if not head or n<1:
return None
hair=ListNode(-1)
hair.next=head
pre=hair
tail=head
while n>0:
tail=tail.next
n-=1
while tail:
hair=hair.next
tail=tail.next
hair.next=hair.next.next
return pre.next