用链表实现栈

2019-05-31  本文已影响0人  成长和自由之路

用链表实现栈,详细代码如下:

package stack;

public class StackByLinkedlist {

    ListNode popNode;

    public boolean push(String item) {
        ListNode temp = popNode;
        popNode = new ListNode(item);
        popNode.next = temp;
        return true;
    }

    public String pop() {
        if (popNode == null) {
            return null;
        }
        String result = popNode.val;
        popNode = popNode.next;
        return result;
    }

    public String peek() {
        if (popNode == null) {
            return null;
        }
        String result = popNode.val;

        return result;
    }

    public boolean empty() {
        return popNode == null;
    }


    class ListNode {
        String val;
        ListNode next;

        ListNode(String x) {
            val = x;
        }
    }

}

复杂度分析

时间复杂度 : push 和 pop 均为:O(1)
空间复杂度 : push 和 pop 均为:O(1)

上一篇下一篇

猜你喜欢

热点阅读