题目描述
给定一个链表,删除链表的倒数第 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:
pre_head=ListNode(1)
pre_head.next=head
a=b=pre_head #a对应倒数第n+1个节点,b对应最后一个节点
if head.next==None:
return None
while n>0:
b=b.next
n-=1
while b.next:
a=a.next
b=b.next
a.next=a.next.next
return pre_head.next
相当于a和b保持n个距离然后同时前进,当b为最后一个元素时,把a后面的元素删去
执行用时 :32 ms, 在所有 Python3 提交中击败了88.03%的用户
内存消耗 :13.5 MB, 在所有 Python3 提交中击败了7.83%的用户
两遍过法
# 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:
pre_head=ListNode(1)
pre_head.next=head
a=b=pre_head #a对应倒数第n+1个节点,b对应最后一个节点
w=0 #n是计数器
while b.next:
w+=1
b=b.next
while w-n>0:
w-=1
a=a.next
a.next=a.next.next
return pre_head.next
b先遍历数组,用w来记录有几个元素,这样就知道应该删除第几个元素了,然后a再往后走直到走到相对应的位置进行删除
执行用时 :40 ms, 在所有 Python3 提交中击败了47.91%的用户
内存消耗 :13.6 MB, 在所有 Python3 提交中击败了7.52%的用户