58-チェーンテーブルの最後からN番目のノード-leetCode 19(python)を削除
: 1->2->3->4->5, n = 2.
, 1->2->3->5.
説明:
与えられた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:
#
#
front = ListNode(0)
front.next,fast,slow = head,front,front
while(n or fast):
if n:
# n
fast,n=fast.next,n-1
else:
# , NULL
# slow
fast = fast.next
if fast:
slow = slow.next
slow.next = slow.next.next
#
return front.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:
length = 0 #
p = head #
while p:
p = p.next
length += 1
idx = length - n # ( 0 )
p = head #
if idx == 0: #
return head.next
for i in range(length):
if i == idx-1: #
p.next = p.next.next
return head
else:
p = p.next # ,