【问题标题】:How to implement a queue with a singly linked list, such that its ENQUEUE and DEQUEUE take O(1)?如何用单链表实现队列,使其ENQUEUE和DEQUEUE取O(1)?
【发布时间】:2014-05-30 09:39:02
【问题描述】:

这是CLRS 3rd的练习:

10.2-3 通过单链表L实现队列。ENQUEUE和DEQUEUE操作仍然需要O(1)时间。

使用单链表实现队列并不难。我的问题是时间复杂度。如何实现 O(1) 的 ENQUEUE 和 DEQUEQUE?

我在 google 上找到的东西类似于使用指针来跟踪头部和尾部。现在问题变成了如何使用 O(1) 时间在单链表上跟踪头尾?恕我直言,跟踪尾巴需要 O(n)。我对吗?

【问题讨论】:

  • 维护两个指针:headtail。在enqueueing 时操作tail,在dequeueing 时操作head

标签: c++ c algorithm data-structures


【解决方案1】:

管理头尾指针需要 O(1) 时间。

入队:

tail -> next = newNode;
newNode -> next = NULL;
tail = newNode;

出队:

output_node = head;
head = head -> next;
// do whatever with output_node;

注意:在执行指针分配之前,您还必须执行边界检查和内存分配/取消分配

【讨论】:

    【解决方案2】:

    这很简单,只需 enque 在末尾和 deque 在前面,然后设置 2 个指向 end 和 front 的指针(或 unique_ptrs)就可以了。像这样:

    struct queue{
        Node *head;
        Node *tail;
        int node_cnt; // well, you can put this in if you like
    };
    
    Node *enque(Node *head, int data)
    {
        Node *p = new Node(Node data);
        if (head)
        {
            head->next = p;
            head = p;
        }
        else
            head = p;
        ++ q.node_cnt;
        return head;
    }
    
    int deque(Node *tail)
    {
        Node *p = tail;
        int x = tail->data;
        tail = tail.next();
        delete p;
        -- q.node_cnt;
        return x;
    }
    

    上面只是一个演示代码,但是您可以看到您不需要遍历整个列表来入队或出队。

    【讨论】:

    • 看起来不错!只是想知道,声明head = x; 中的x 是什么?是p吗?
    • 感谢指出,我只是手写代码,没有做任何检查,抱歉。我假设 Node 是具有此签名的结构: struct Node { int data;节点 *next;节点(int a):数据(a){} };所以,它应该是 x = p->data;类似的东西。
    【解决方案3】:

    std::list 是您正在寻找的,如果您被允许使用 std 容器。

    如果不是(我假设是这种情况),请尝试回答以下问题:为什么需要执行 n 次操作?你能把指针存储到末尾吗?

    说,你有一个符号链表和一个指针headtail 列表项有next 指针。

    • 如果您将一个新项目加入队列,您只需添加一个新项目,修改前“第一个”项目的next 指针并将head 指针重新指向新项目。那是 3 次操作 = O(1)
    • 如果您使一个项目出队,则将 last 指针移动到最后一个项目的 next 指针所指向的那个,然后删除该项目 - 2 次操作 = O(1)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-15
      • 1970-01-01
      • 2020-04-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多