【问题标题】:Implementing Stacks and Queues using a Linked List使用链表实现堆栈和队列
【发布时间】:2015-05-15 04:30:30
【问题描述】:

我正在尝试在我的计算机科学课上复习之前关于链接列表的一些家庭作业问题。这个问题真的困扰着我应该如何解决这个问题,它希望我使用我不久前制作的 Linked List 类来实现一个“Stack”和一个“Queue”类。这就是所有的问题状态,所以我必须使用我的 ListNode 类吗?

class ListNode(object):

    def __init__(self, item = None, link = None):

        '''creates a ListNode with the specified data value and link
        post: creates a ListNode with the specified data value and link'''

        self.item = item
        self.link = link

我将如何制作一个可以推送和弹出的堆栈类?我的代码会是这样吗?还是会离题?

from ListNode import ListNode

class LinkedStack(object):
    def __init__(self, ListNode.item):
        stack = []
    def push(self,item):
        self.append(ListNode.item)
        self.size += 1
    def isEmpty(self):
        return not self

我只是基于我在此网页上看到的示例代码。根据链表制作一个简单的堆栈类有什么帮助吗?出于某种原因,它希望我使用给我的这个类来测试我的代码。

def isPalindrome(phrase):
    forward = Queue()
    reverse = Stack()
    extractLetters(phrase, forward, reverse)
    return sameSequence(forward, reverse)

#------------------------------------------------------------

def extractLetters(phrase, q, s):
    for ch in phrase:
        if ch.isalpha():
            ch = ch.lower()
            q.enqueue(ch)
            s.push(ch)

#------------------------------------------------------------

def sameSequence(q, s):
    while q.size() > 0:
        ch1 = q.dequeue()
        ch2 = s.pop()
        if ch1 != ch2:
            return False
    return True

感谢任何提前帮助我的人!

【问题讨论】:

  • 堆栈添加到末尾,从末尾删除。队列添加到末尾,从头部删除。除此之外,没有什么可考虑的了。
  • 你能写一个我可以为我的堆栈和队列类做的代码示例吗?对不起,我一直对这个领域感到困惑,这就是我重新审视它的原因
  • 你真的是说你不理解链表头部或尾部插入和删除的概念吗?
  • @MarkRansom 抱歉,我对编码还很陌生,您不必对此感到厌烦。我只是想理解这一点。
  • 而我正在努力了解您不了解的内容。看来您可能对链表的概念完全有疑问,但在这一点上我不能说。一旦你有了一个工作链表,在它上面构建一个堆栈或队列是微不足道的。

标签: python linked-list stack queue


【解决方案1】:

使用 python list 创建堆栈的一种方法是使用 list 的 append 和 pop 函数。

示例堆栈类:

class stack(object):
    def __init__(self):
        self.data = []

    def pop(self):
        if self.isEmpty():
            print "Nothing to remove from stack"
            return None
        return self.data.pop()

    def push(self, item):
        self.data.append(item)

    def isEmpty(self):
        if len(self.data) == 0:
            return True
        return False


s = stack()
s.push(1)
s.push(2)
s.push(3)
print s.pop()
print s.pop()
print s.pop()
print s.pop()

输出:

3
2
1
Nothing to remove from stack
None

【讨论】:

  • 我知道这可行,但我需要在其中添加我的列表节点,因为它仍然需要使用我的链表。
猜你喜欢
  • 2015-11-16
  • 2021-07-08
  • 2011-07-29
  • 2014-12-23
  • 2010-10-15
  • 1970-01-01
  • 2019-03-07
  • 2018-06-14
相关资源
最近更新 更多