【问题标题】:Implement Python stack using linked list and access the items in the stack使用链表实现 Python 堆栈并访问堆栈中的项目
【发布时间】: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


【解决方案1】:
  1. 您想要的不是Stack。这是Priority QueueHeap

  2. 有些动物比大象重,比豹子轻。你怎么知道用户会将哪种动物推入堆栈?所以您在Node 类中使用的数据可能是一个字典,其最简单的形式是带有size 键。

    class Node:
    
         def __init__(self, name: str, size: int):
              animal_data = {'name': name, 'size': size}
              self.data = animal_data
              self.next = None
    
  3. 当您将新数据推送到Stack 时,您必须按data 类中data 属性中的size 键对堆栈进行排序。因此,无论何时显示堆栈,都会首先显示较重的动物。

  4. 要返回第一个元素,您可以使用self.head 属性,但对于最后一个元素,您必须更改链表的结构。您使用的这种类型的链表是Singly Linked List,但您必须使用Doubly Linked List,它有一个名为Tail 的额外属性,并且当Pushing 进入堆栈和Popping 来自堆栈时会有不同的行为。

  5. Python 有 heapq 模块,可以用 list 实现你想要的一切。要拥有HeapLinked List,您必须自己实现它。还有deque 模块,它是双链表的堆栈和队列的实现。

您可以在这里阅读更多关于 Python 中的堆、队列和堆栈的信息:

【讨论】:

  • 感谢您的反馈。问题是我被分配的一项任务,主要关注 Big 5 动物。在您回答的第 2 项上,您问我用户如何确定要推动哪种动物,因为它们是比大象大的动物,但我的重点主要是 5 大动物 [“大象”、“犀牛”、“狮子”、 “豹” ]。因此,在将动物插入链表后,如何在对链表进行升序排序后打印第一个元素和最后一个元素。
  • 列表升序排序后,self.head 将指向LeopardElephant 将位于列表末尾。所以你必须迭代抛出列表直到你到达最后,然后你可以返回最后一个项目。你也可以使用这个技巧 -> Find the Kth Node from the end in a given singly Linked List.
猜你喜欢
  • 2021-11-16
  • 2011-07-29
  • 2013-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-10
  • 2012-05-24
相关资源
最近更新 更多