This code is based off the Stack implementation in Chapter 3 of Cracking The Coding Interview. I modified the code to make it compile and give me the correct output. I'd appreciate any feedback on code style and correctness, assuming that I write this code in a technical interview.
The pseudocode from Cracking the Coding Interview, which is implemented using a linked list:
class Stack { Node top; Object pop() { if (top != null) { Node item = top.data; top = top.next; return item; } return null; } void push(Object item) { Node t = new Node(item); t.next = top; top = t; } Object peek() { return top.data; } }
My code:
public class Stack {
Node first;
Node last;
public Stack(Node f, Node l) {
first = f;
last = l;
first.next = last;
}
public Stack() {
first.next = last;
}
public void push(Object data) {
if(first == null) {
first = new Node(data, null);
}
else {
last.next = new Node(data, null);
last = last.next;
}
}
public Object pop() {
if(first == null) {
return -1;
}
else {
Object item = last.data;
Node cur = first;
while (cur.next.next != null) {
cur = cur.next;
}
last = cur;
return item;
}
}
public Object peek() {
if(first == null) {
return -1;
}
Object item = last.data;
return item;
}
public static void main(String[] args) {
Stack stack = new Stack(new Node(1, null), new Node(2, null));
stack.push(3);
System.out.println(stack.peek() == 3);
stack.pop();
System.out.println(stack.peek() == 2);
}
private static class Node {
Object data;
Node next;
private Node(Object d, Node n) {
data = d;
next = n;
}
}
}