Google interview question

Implement the stack structure and its functions (push, pop, empty)

Interview Answers

Anonymous

7 Apr 2015

I used a vector (in c++) as the container for the stack. I also used template.

Anonymous

13 Apr 2015

package interviewQuestions; import java.util.ArrayList; import java.util.List; public class StackX> { private List arr; private int top; public StackX() { top=-1; arr=new ArrayList(); } public void push(T item) { arr.add(item); top++; } public boolean isEmpty() { return (top==0); } public T pop() { T cur=arr.get(top); arr.remove(top); top--; return cur; } public T peek() { if(top>0) return arr.get(top); else return null; } public static void main(String[] args) { StackX s=new StackX(); s.push("ABC"); s.push("BBC"); s.push("CBC"); s.push("DBC"); System.out.println(s.isEmpty()); System.out.println(s.peek()); System.out.println(s.pop()); s.push("EBC"); System.out.println(s.pop()); } }