题目
解答一
代码
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
r=head
b=head
while n:
b=b.next
n-=1
if b==None:
head=head.next
return r.next
while b!=None:
if b.next==None:
head.next=head.next.next
b=b.next
head=head.next
return r
思路
两个指针,第一个遍历链表,第二个在第一个遍历完后通过两者间隔找到删除点进行删除。
结果
时间复杂度:O(n)
解答二
代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head, n):
global count
if head is None:
count=0
return None
head.next=self.removeNthFromEnd(head.next,n)
count+=1
return head.next if n==count else head
思路
递归法