【发布时间】:2022-01-25 00:29:22
【问题描述】:
我正在尝试使用链表实现堆栈。我已经编写了下面的代码,请您帮忙改进代码我想插入五只大动物的名字并按大小顺序排列 => 如下大象(约 5 吨 +) , 犀牛 (约 2 吨)、Buffalo(650 公斤)、Lion(225 公斤)和 Leopard(96 公斤)。
我该如何进行以下操作
1.返回第一个和最后一个元素(动物名称) 当元素按升序排序时
下面是我的代码
class Node:
# Class to create nodes of linked list
# constructor initializes node automatically
def __init__(self,data):
self.data = data
self.next = None
class Stack:
# head is default NULL
def __init__(self):
self.head = None
# Checks if stack is empty
def isempty(self):
if self.head == None:
return True
else:
return False
# Method to add data to the stack
# adds to the start of the stack
def push(self,data):
if self.head == None:
self.head=Node(data)
else:
newnode = Node(data)
newnode.next = self.head
self.head = newnode
def find_animal(self, data):
big_head = self.head
index = 0
while big_head.next:
if big_head.data == data:
print(f'{big_head.data} at index {index}')
index += 1
big_head = big_head.next
# Remove element that is the current head (start of the stack)
def pop(self):
if self.isempty():
return None
else:
# Removes the head node and makes
#the preceding one the new head
poppednode = self.head
self.head = self.head.next
poppednode.next = None
return poppednode.data
# Returns the head node data
def peek(self):
if self.isempty():
return None
else:
return self.head.data
# Prints out the stack
def display(self):
iternode = self.head
if self.isempty():
print("Stack Underflow")
else:
while(iternode != None):
print(iternode.data,"->",end = " ")
iternode = iternode.next
return
# Driver code
The_Big_Five = Stack()
The_Big_Five.push("Leopard")
The_Big_Five.push("Lion")
The_Big_Five.push("Buffalo")
The_Big_Five.push("Rhinoceros")
The_Big_Five.push("Elephant")
# Code for printing linked list
The_Big_Five.display()
# Code for sorting the linked list
sorted_Big_5 =sorted(The_Big_Five)
#Printing the sorted list
print(sorted_Big_5)
#Printing the first element of the sorted linked list
print(sorted_Big_5[0])
#printing the last element of the sorted linked list
print(sorted_Big_5[-1])
【问题讨论】:
-
这个问题太笼统了。请关注一个具体的问题,并解释出了什么问题(一件事!)以及如何重现该问题。
-
@trincot 我主要想知道如何打印链接列表中的任何选定项目,特别是第一个和最后一个元素。
-
那么,您能否更新您的问题以使其仅关注一个问题,并在问题中提供我们重现该问题所需的内容?使用问题下方的编辑链接。
-
所以你想排序?我没有在您的代码中看到您尝试排序的位置,以及您在尝试时遇到的问题。
-
@trincot 我不知道如何对链表进行排序(这是我需要帮助的代码),排序后我想打印第一个和最后一个元素。那么如何改进我的代码,以便它可以执行我打算做的事情呢?请寻求您的帮助
标签: python python-3.x data-structures linked-list stack