使用遞迴反轉棧的Python程式
當需要使用遞迴反轉棧資料結構時,除了新增值、刪除值和列印棧元素的方法外,還定義了一個“stack_reverse”方法。
以下是相同的演示 -
示例
class Stack_structure: def __init__(self): self.items = [] def check_empty(self): return self.items == [] def push_val(self, data): self.items.append(data) def pop_val(self): return self.items.pop() def print_it(self): for data in reversed(self.items): print(data) def insert_bottom(instance, data): if instance.check_empty(): instance.push_val(data) else: deleted_elem = instance.pop_val() insert_bottom(instance, data) instance.push_val(deleted_elem) def stack_reverse(instance): if not instance.check_empty(): deleted_elem = instance.pop_val() stack_reverse(instance) insert_bottom(instance, deleted_elem) my_instance = Stack_structure() data_list = input('Enter the elements to add to the stack: ').split() for data in data_list: my_instance.push_val(int(data)) print('The reversed stack is:') my_instance.print_it() stack_reverse(my_instance) print('The stack is:') my_instance.print_it()
輸出
Enter the elements to add to the stack: 23 56 73 81 8 9 0 The reversed stack is: 0 9 8 81 73 56 23 The stack is: 23 56 73 81 8 9 0
解釋
建立一個名為“Stack_structure”的類,該類初始化一個空列表。
定義一個“check_empty”方法來檢視棧是否為空。
定義另一個名為“push_val”的方法,該方法將元素新增到棧中。
定義另一個名為“pop_val”的方法,該方法從棧中刪除元素。
定義一個名為“print_it”的方法,該方法有助於列印棧的元素。
定義一個名為“insert_bottom”的方法,該方法將元素新增到棧的底部,而不是預設新增到頂部。
定義另一個名為“stack_reverse”的方法,該方法有助於反轉給定的棧。
定義此“Stack_structure”的一個例項。
從使用者處獲取棧的元素。
對其進行迭代,並呼叫方法將值新增到棧中並在控制檯上列印。
現在,在這個列表上呼叫“stack_reverse”。
呼叫“print_it”以在控制檯上顯示反轉的棧。
廣告