Python程式:僅反轉連結串列的前N個元素


當需要反轉連結串列中的特定元素集時,定義了一個名為“reverse_list”的方法。它迭代遍歷列表,並反轉特定元素集。

下面是相同的演示 -

示例

 線上演示

class Node:
   def __init__(self, data):
      self.data = data
      self.next = None

class LinkedList_structure:
   def __init__(self):
      self.head = None
      self.last_node = None

   def add_vals(self, data):
      if self.last_node is None:
         self.head = Node(data)
         self.last_node = self.head
      else:
         self.last_node.next = Node(data)
         self.last_node = self.last_node.next

   def print_it(self):
      curr = self.head
      while curr:
         print(curr.data)

         curr = curr.next
def reverse_list(my_list, n):
   if n == 0:
      return
   before_val = None
   curr = my_list.head
   if curr is None:
      return
   after_val = curr.next
   for i in range(n):
      curr.next = before_val
      before_val = curr
      curr = after_val
      if after_val is None:
         break
      after_val = after_val.next
   my_list.head.next = curr
   my_list.head = before_val

my_instance = LinkedList_structure()
my_list = input('Enter the elements of the linked list... ').split()
for elem in my_list:
   my_instance.add_vals(int(elem))
n = int(input('Enter the number of elements you wish to reverse in the list... '))

reverse_list(my_instance, n)

print('The new list is : ')
my_instance.print_it()

輸出

Enter the elements of the linked list... 45 67 89 12 345
Enter the number of elements you wish to reverse in the list... 3
The new list is :
89
67
45
12
345

解釋

  • 建立“Node”類。

  • 建立另一個具有所需屬性的“LinkedList_structure”類。

  • 它有一個“init”函式,用於將第一個元素(即“head”)初始化為“None”。

  • 定義了一個名為“add_vals”的方法,用於向棧新增值。

  • 定義了另一個名為“print_it”的方法,用於在控制檯上顯示連結串列的值。

  • 定義了另一個名為“reverse_list”的方法,用於反轉連結串列的特定元素集。

  • 建立“LinkedList_structure”的例項。

  • 將元素新增到連結串列中。

  • 在控制檯上顯示元素。

  • 從使用者處獲取需要反轉的元素數量。

  • 在這個連結串列上呼叫“reverse_list”方法。

  • 在控制檯上顯示輸出。

更新於:2021年4月14日

149 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.