【问题标题】:Writing pop() method for LinkedStack in O(1)在 O(1) 中为 LinkedStack 编写 pop() 方法
【发布时间】:2018-07-15 23:30:36
【问题描述】:

如何在 O(1) 中为 LinkedStack 编写 pop() 方法? 我的LinkedStack 类中有两个私有数据成员:ListNode* headListNode* tail

head 指向LinkedStack 的开头,tail 指向LinkedStack 的结尾。

pop() 将删除tail 指向的ListNode,然后tail 将指向之前 tailListNode

知道了这一点,我将如何在O(1) 中写入pop()?显然,我可以编写一个 for 循环,在 tail 之前抓取前一个 ListNode,但随后 pop() 不会是 O(1)

由于这是家庭作业,我不是在寻找代码解决方案,只是可能是正确方向的提示。

编辑:我可能看到的一个解决方案是拥有一个ListNode* prev 数据成员,它始终指向tail 之前的前一个ListNode。但我觉得有一种更有效的方法....

Edit2:谢谢@user4581301。 假设LinkedStack为空时不会调用pop()

【问题讨论】:

  • @user4581301 感谢您提及!假设链表为空时不会调用pop。
  • O(1) 解决方案(在这里做一些假设):ListNode* temp = tail; tail = tail->prev; delete temp; 如果您不能这样做,请重新考虑您的链表逻辑,因为某些内容已损坏或过于复杂。如果你想返回节点上的内容,你必须做更多的工作。请注意,标准库的堆栈不会从 pop 返回任何内容,以避免这种额外的工作以及随之而来的一些麻烦。 Link to related question that covers some of the nastiness.
  • 天哪。我很抱歉。我什至没有考虑单链表。是的,你试图用尾巴做的事情是不可能的,这可能是我的大脑过滤掉它并假设双向链表的原因。我应该阅读您的问题编辑。

标签: c++ linked-list stack big-o


【解决方案1】:

正如您所说,任何您必须遍历列表以定位特定元素的情况将使恒定时间要求无法满足。这包括一个单链表,您将项目推到最后。 双向链接列表会更容易,因为您无需遍历即可从尾部到达倒数第二项。

但是,我不确定为什么你要坚持到底。如果您要在列表的 front 上推送新元素,那么实现 pushpop 的恒定时间是微不足道的。

我的意思是(伪代码,因为正如你提到的,“这是为了家庭作业”):

def push(x):
    allocate node          # get new node and set data.
    node.data = x

    node.next = head       # insert at head of list
    head = node

def pop():
    assert head != null    # catch pop on empty stack

    node = head            # get first node and data
    retval = node.data

    head = head.next       # set head to be second node

    free node              # free node and return data
    return retval

您可以看到对于任一操作都没有遍历列表。首先,将7 推到一堆素数上:

Starting list:
    head
        \
         5 -> 3 -> 2 -|

Create new node, point to current head:
     head
         \
     7 -> 5 -> 3 -> 2 -|

Point head at new node:
    head
        \
         7 -> 5 -> 3 -> 2 -|

现在让我们弹出相同的值。

Starting list:
    head
        \
         7 -> 5 -> 3 -> 2 -|

Save head as node, and value to return (7):
    head
        \
         7 -> 5 -> 3 -> 2 -|
        /
    node

Adjust head:
         head
             \
         7 -> 5 -> 3 -> 2 -|
        /
    node

Free node and return stored value (7):
    head
        \
         5 -> 3 -> 2 -|

【讨论】:

    猜你喜欢
    • 2022-10-13
    • 2011-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-10
    • 2021-05-04
    • 2023-04-01
    • 2019-07-30
    相关资源
    最近更新 更多