在Java中使用链接列表实现stack [译]

来源:互联网 发布:淘宝发货后买家退款 编辑:程序博客网 时间:2024/06/14 23:08

https://www.java2blog.com/implement-stack-using-linked-list-in-java/



在这个程序中,我们将看到如何在java中使用链表来实现堆栈。
堆栈是演示后进先出(LIFO)行为的抽象数据类型。我们将使用链接列表来实现相同的行为。
Stack有两个最重要的操作:

推:我们将元素推送到链表的开头来演示堆栈的推送行为。
Pop:我们将删除链表的第一个元素来演示Stack的弹出行为。
Java程序:

让我们创建一个Java程序来使用链接列表创建堆栈。

LinkedListStack

package demo;/** * 如果你想练习数据结构和算法程序,你可以通过  数据结构和算法面试的问题。 * <p> * 在这个程序中,我们将看到如何在java中使用链表来实现堆栈。 * 堆栈是演示后进先出(LIFO)行为的抽象数据类型。我们将使用链接列表来实现相同的行为。 * <p> * Stack有两个最重要的操作: * push:我们将元素推送到链表的开头来演示堆栈的推送行为。 * pop:我们将删除链表的第一个元素来演示Stack的弹出行为。 * <p> * Java程序: * 让我们创建一个Java程序来使用链接列表创建堆栈。 */public class LinkedListStack {    /**     * 嵌套类 node     */    private class Node {        int value;        Node next;    }    private Node head; // 最上面的节点    public LinkedListStack() {        this.head = null;    }    public void push(int pushValue) {        Node oldHead = head;        head = new Node();        head.value = pushValue;        head.next = oldHead;        System.out.println("push :" + pushValue);    }    public int pop() throws LinkedListEmptyException {        if (head == null) {            throw new LinkedListEmptyException();        }        int popValue = head.value;        head = head.next;        System.out.println("pop :" + popValue);        return popValue;    }    public void printList() {        Node temp = head;        while (temp != null) {            System.out.format("%d ", temp.value);            temp = temp.next;        }        System.out.println("is end .............");    }}class LinkedListEmptyException extends RuntimeException {    private static final long serialVersionUID = 1L;    public LinkedListEmptyException() {        super();    }    public LinkedListEmptyException(String message) {        super(message);    }}

TestLinkedListStack

package demo;public class TestLinkedListStack {    public static void main(String[] args) {        LinkedListStack lls = new LinkedListStack();        lls.push(20);        lls.push(50);        lls.push(80);        lls.push(40);        lls.push(60);        lls.push(75);        lls.printList();        lls.pop();        lls.pop();        lls.printList();        lls.push(10);        lls.printList();        lls.pop();        lls.printList();    }}

输出结果

push :20push :50push :80push :40push :60push :7575 60 40 80 50 20 is end .............pop :75pop :6040 80 50 20 is end .............push :1010 40 80 50 20 is end .............pop :1040 80 50 20 is end .............Process finished with exit code 0

end

原创粉丝点击