Problem
Implement a stack. You can use any data structure inside a stack except stack itself to implement it.
Example
push(1)
pop()
push(2)
top() // return 2
pop()
isEmpty() // return true
push(3)
isEmpty() // return false
Solution
class ListNode {
int val;
ListNode next;
public ListNode(int val) {
this.val = val;
}
}
public class Stack {
ListNode head;
public Stack() {
head = new ListNode(0);
head.next = null;
}
public void push(int x) {
ListNode node = new ListNode(x);
node.next = head.next;
head.next = node;
}
/*
* @return: nothing
*/
public void pop() {
if (head.next != null) {
head.next = head.next.next;
}
}
/*
* @return: An integer
*/
public int top() {
return head.next.val;
}
/*
* @return: True if the stack is empty
*/
public boolean isEmpty() {
return head.next == null;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。