Python 程式建立包含 n 個節點的雙向連結串列並在反向順序中顯示
當需要建立雙向連結串列並以反向順序顯示元素時,需要建立一個“節點”類。在這個類中,有三個屬性,節點中存在的資料,對連結串列中下一個節點的訪問以及對連結串列中前一個節點的訪問。
需要建立另一個類,該類將具有初始化函式,並且節點的頭將在其中初始化為“None”。
使用者定義了多種方法來向連結串列新增節點,反轉節點並在連結串列中列印節點。
以下是相同的演示 -
示例
class Node:
def __init__(self, my_data):
self.prev = None
self.data = my_data
self.next = None
class reverse_list:
def __init__(self):
self.head = None
self.tail = None
def add_data(self, my_data):
new_node = Node(my_data)
if(self.head == None):
self.head = self.tail = new_node;
self.head.previous = None;
self.tail.next = None;
else:
self.tail.next = new_node;
new_node.previous = self.tail;
self.tail = new_node;
self.tail.next = None;
def reverse_vals(self):
curr = self.head;
while(curr != None):
temp = curr.next
curr.next = curr.previous
curr.previous = temp
curr = curr.previous
temp = self.head
self.head = self.tail
self.tail = temp
def print_it(self):
curr = self.head
if (self.head == None):
print("The list is empty")
return
print("The nodes are :")
while curr != None:
print(curr.data)
curr = curr.next
my_instance = reverse_list()
print("Elements are being added to the list")
my_instance.add_data(10)
my_instance.add_data(14)
my_instance.add_data(24)
my_instance.add_data(17)
my_instance.add_data(22)
my_instance.print_it()
print("The reversed nodes in the doubly linked list are : ")
my_instance.reverse_vals()
my_instance.print_it()輸出
Elements are being added to the list The nodes are : 10 14 24 17 22 The reversed nodes in the doubly linked list are : The nodes are : 22 17 24 14 10
解釋
- 建立了“節點”類。
- 建立了另一個具有所需屬性的類。
- 定義了一個名為“add_data”的方法,用於將資料新增到雙向連結串列。
- 定義了另一個名為“reverse_node”的方法,該方法有助於反轉雙向連結串列中節點的順序。
- 定義了另一個名為“print_it”的方法,該方法顯示迴圈連結串列的節點。
- 建立了“reverse_list”類的物件,並在其上呼叫方法以反轉雙向連結串列的節點。
- 定義了一個“init”方法,將雙向連結串列的根、頭和尾節點設定為 None。
- 呼叫了“reverse_vals”方法。
- 它遍歷雙向連結串列,並反轉列表。
- 這使用“print_it”方法在控制檯上顯示。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP