Implement Stack(lintcode 495)
Description
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
Interface
class Stack {
// Push a new item into the stack
public void push(int x) {
// Write your code here
}
// Pop the top of the stack
public void pop() {
// Write your code here
}
// Return the top of the stack
public int top() {
// Write your code here
}
// Check the stack is empty or not.
public boolean isEmpty() {
// Write your code here
}
}
Solution
class Stack {
private ListNode head;
// Push a new item into the stack
public void push(int x) {
// Write your code here
ListNode newHead = new ListNode(x);
newHead.next = head;
head = newHead;
}
// Pop the top of the stack
public void pop() {
// Write your code here
if (head == null) {
throw new NoSuchElementException();
}
head = head.next;
}
// Return the top of the stack
public int top() {
// Write your code here
if (head == null) {
throw new NoSuchElementException();
}
return head.val;
}
// Check the stack is empty or not.
public boolean isEmpty() {
// Write your code here
return head == null;
}
}