栈的链表实现

链表:
`class ListNode {
int val;
ListNode next;

public ListNode(int val) {
    this.val = val;
}

}

class LinkedStack {
private ListNode top;

public void push(int item) {
    ListNode newNode = new ListNode(item);
    newNode.next = top;
    top = newNode;
}

public int pop() {
    if (top == null) {
        throw new IllegalStateException("Stack is empty");
    }
    int value = top.val;
    top = top.next;
    return value;
}

public boolean isEmpty() {
    return top == null;
}

}`

posted @ 2024-10-17 23:14  最爱菠萝  阅读(4)  评论(0编辑  收藏  举报