-
问题
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。
进阶:
你能尝试使用一趟扫描实现吗? -
解答
class Solution(object):
def l(self, head):
size = 0
h = head
while h:
size += 1
h = h.next
return size
def removeNthFromEnd(self, head, n):
if n == 1 and head.next is None:
return None
if n == 1 and head.next.next is None:
head.next = None
return head
if n == self.l(head):
head = head.next
return head
slow, fast = head, head
step = 0
while step < n:
fast = fast.next
step += 1
while fast and fast.next:
fast = fast.next
slow = slow.next
if slow == head:
head.next = head.next.next
return head
slow.next = slow.next.next
return head
- 解答
class Solution(object):
def l(self, head):
size = 0
h = head
while h:
size += 1
h = h.next
return size
def removeNthFromEnd(self, head, n):
size = self.l(head)
if size == n:
head = head.next
return head
step = 0
start = head
while step < size - n - 1:
step += 1
start = start.next
start.next = start.next.next
return head