题目信息

解题思路

计算链表长度(容易想到)

快慢指针

删除链表节点

代码

计算链表长度

  # class ListNode:
  #     def __init__(self, val=0, next=None):
  #         self.val = val
  #         self.next = next
  class Solution:
	  def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
		  p = head
		  l = 0
		  # get the length of the linked list L
		  while p != None:
			  l += 1
			  p = p.next
		  # find the L-N node's pointer
		  # then remove the L-N+1 node
		  if l-n == 0:
			  # if l-n == 0, remove head node
			  dummy = ListNode()
			  dummy.next = head
			  p = dummy
			  p.next = p.next.next
			  return dummy.next
		  cnt = 0
		  p = head
		  while p != None:
			  cnt += 1
			  if cnt == l-n:
				  # current p points to L-N
				  p.next = p.next.next
				  break
			  p = p.next
		  return head

快慢指针

  # Definition for singly-linked list.
  # class ListNode:
  #     def __init__(self, val=0, next=None):
  #         self.val = val
  #         self.next = next
  class Solution:
	  def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
		  # find (N+1)th from the end of the list
		  dummy = ListNode(next=head)
		  fast, slow = dummy, dummy
		  # fast pointer start from n+1 nodes ahead
		  for _ in range(n+1):
			  fast = fast.next
		  # slow is the target node when fast points to the end
		  while fast is not None:
			  slow = slow.next
			  fast = fast.next
		  # remove node
		  # n>=1 slow is at least the 2nd node from the end, slow.next will not be None
		  slow.next = slow.next.next
		  return dummy.next