leetcode 提交
方法一:一次遍历(快慢指针)
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
dummy = ListNode(0, head) # 一次遍历,快慢指针
slow, fast = dummy, dummy
while n:
fast = fast.next
n -= 1
while fast.next:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return dummy.next
方法二:两次遍历
写法一: 直接删除,注意“头结点”需要特殊处理一下。
class Solution(object):
def removeNthFromEnd(self, head, n): # 最简单的:两次遍历
num, p = 0, head
while p:
num += 1
p = p.next
p = head
if num == n and p.next == None: # 仅有一个节点
return None
elif num == n: # 删除头节点
head = head.next
for i in range(num-1):
if i == num - n - 1:
q = p.next
p.next = q.next
else:
p = p.next
return head
写法二:在头结点之前加个哑变量,统一所有结点的操作。
class Solution(object):
def removeNthFromEnd(self, head, n):
num, p = 0, head
while p:
num += 1
p = p.next
dummy = ListNode(0, head)
p = dummy
for i in range(1, num-n+1):
p = p.next
p.next = p.next.next
return dummy.next
本地测试
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def createLinkList(lst):
head = ListNode(lst[0])
p = head
for i in range(1, len(lst)):
p.next = ListNode(lst[i])
p = p.next
return head
def printList(head):
p = head
lst = []
while p:
lst.append(p.val)
p = p.next
return lst
class Solution(object): # 写法一
def removeNthFromEnd(self, head, n): # 最简单的:两次遍历
num, p = 0, head
while p:
num += 1
p = p.next
p = head
if num == n and p.next == None: # 仅有一个节点
return None
elif num == n: # 删除头节点
head = head.next
for i in range(num-1):
if i == num - n - 1:
q = p.next
p.next = q.next
else:
p = p.next
return head
# class Solution(object): # 写法二
# def removeNthFromEnd(self, head, n):
# num, p = 0, head
# while p:
# num += 1
# p = p.next
# dummy = ListNode(0, head)
# p = dummy
# for i in range(1, num-n+1):
# p = p.next
# p.next = p.next.next
# return dummy.next
# t = [1,2,3,4,5]
# t = [1]
# t = [1,2]
t = [1,2,3,4,5,6]
n = 6
linklist = createLinkList(t)
s = Solution()
s = s.removeNthFromEnd(linklist, n)
printList(s)