Python 中移除链表的倒数第 N 个节点


假设我们有一个链表。我们必须移除链表的倒数第 N 个节点,然后返回其头部。因此,如果列表类似于 [1, 2, 3, 4, 5, 6] 并且 n = 3,则返回的列表将为 [1, 2, 3, 5, 6]。

为了解决这个问题,我们将遵循以下步骤:

  • 如果头部之后没有节点,则返回 None
  • front := head,back := head,counter := 0,found := false
  • 当 counter <= n 时
    • 如果 front 不存在,则将标志设置为 true,并退出循环
    • front := front 的下一个节点,并将 counter 加 1
  • 当 front 存在时
    • front := front 的下一个节点
    • back := back 的下一个节点
  • 如果标志为 false,则
    • temp := back 的下一个节点
    • back 的下一个节点 := temp 的下一个节点
    • temp 的下一个节点 := None
  • 否则 head := head 的下一个节点
  • 返回 head

示例(Python)

让我们看看下面的实现,以便更好地理解:

 在线演示

class ListNode:
   def __init__(self, data, next = None):
      self.val = data
      self.next = next
def make_list(elements):
   head = ListNode(elements[0])
   for element in elements[1:]:
      ptr = head
      while ptr.next:
         ptr = ptr.next
      ptr.next = ListNode(element)
   return head
def print_list(head):
   ptr = head
   print('[', end = "")
   while ptr:
      print(ptr.val, end = ", ")
      ptr = ptr.next
   print(']')
class Solution(object):
   def removeNthFromEnd(self, head, n):
      if not head.next:
         return None
      front=head
      back = head
      counter = 0
      flag = False
      while counter<=n:
         if(not front):
            flag = True
            break
         front = front.next
         counter+=1
      while front:
         front = front.next
         back = back.next
      if not flag:
         temp = back.next
         back.next = temp.next
         temp.next = None
      else:
         head = head.next
      return head
head = make_list([1,2,3,4,5,6])
ob1 = Solution()
print_list(ob1.removeNthFromEnd(head, 3))

输入

[1,2,3,4,5,6]
3

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

输出

[1,2,3,5,6]

更新于:2020年4月27日

604 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告