【问题标题】:Stack Operations With Linked LIst in JavaJava中链表的栈操作
【发布时间】:2013-04-11 21:55:44
【问题描述】:

我必须编写一个应该使用链表实现堆栈的类。但是,它应该从列表的尾部而不是头部执行推送和弹出操作。此外,它不应该维护对列表尾节点的引用。

在不保留对最后一个节点的引用的情况下,我到底如何实现这一点??

【问题讨论】:

  • 你总是可以遍历一个列表直到它的尾部。尽管不保留对最后一个节点的引用效率最低。
  • 这叫做队列。是的,每次都遍历列表。
  • 我想你对什么是头部和什么是尾部感到困惑
  • 我知道这是低效的,但这就是任务...

标签: java linked-list stack


【解决方案1】:

可以这样做,但是效率很低,因为每次你想做某事时都必须遍历整个列表。当所有操作都在尾部执行时,您确实没有任何理由要保留对头部的引用。

但无论如何我都会这样做:

class Entry<E> {
    E object;
    Entry<E> next;
    public Entry(E obj) {
        object = obj;
    }
}

class StackList<E> {
    Entry<E> head;
    public void push(E element) {
        if (head == null) {
            // first
            head = new Entry<E>(element);
            return;
        }
        Entry<E> node = head;
        while (node != null && node.next != null) {
            node = node.next;
        }
        // node is now the tail
        Entry<E> newEntry = new Entry<E>(element);
        node.next = newEntry;
    }
    public E pop() {
        if (head == null) {
            // empty
            return null;
        }
        Entry<E> node = head, previousNode = null;
        while (node.next != null) {
            previousNode = node;
            node = node.next;
        }
        // node is now the tail
        // previousNode is the next-to-last
        if (previousNode != null) {
            previousNode.next = null;
        } else {
            // there was only one thing
            head = null;
        }
        return node.object;
    }
}

【讨论】:

    猜你喜欢
    • 2013-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-17
    • 2016-10-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多