(신입사원채용무료교육, 오라클SQL, 튜닝, 힌트,자바프레임워크, 안드로이드, 아이폰, 닷넷)
public class EmptyStackException extends RuntimeException {
public EmptyStackException() {
super ("The stack is empty.");
}
public EmptyStackException (String message) {
super (message);
}
}
class ChainNode {
Object element;
ChainNode next;
ChainNode() {}
ChainNode(Object element) { this.element = element;}
ChainNode(Object element, ChainNode next) {
this.element = element; this.next = next;
}
}
public class LinkedStack implements Stack {
protected ChainNode topNode;
/** create an empty stack */
public LinkedStack() {
topNode = new ChainNode();
}
/** return true if stack is empty */
public boolean isEmpty() {
return topNode.next == null;
}
/** return top element of stack
* throws EmptyStackException when the stack is empty */
public Object peek() {
if (isEmpty()) throw new EmptyStackException();
return topNode.next.element;
}
/** add theElement to the top of the stack */
public void push(Object theElement) {
ChainNode p = new ChainNode(theElement, null);
p.next = topNode.next;
topNode.next = p;
}
/** remove top element of stack and return it
* throws EmptyStackException when the stack is empty */
public Object pop() {
if (isEmpty()) throw new EmptyStackException();
Object topElement = topNode.next.element;
topNode.next = topNode.next.next;
return topElement;
}
public String toString() {
StringBuffer sb = new StringBuffer("[");
ChainNode p = topNode.next;
do {
if (p.element == null) sb.append("null");
else sb.append(p.element.toString());
p = p.next;
if (p != null) sb.append(",");
} while (p != null);
sb.append("]");
return sb.toString();
}
}
public class Main {
public static void main(String args[]) {
LinkedStack myStack = new LinkedStack();
myStack.push("a");
myStack.push("b");
myStack.push("c");
System.out.println(myStack);
myStack.pop();
System.out.println(myStack);
System.out.print("현재 top pointer의 data : ");
System.out.println(myStack.peek());
}
}
interface Stack {
public boolean isEmpty();
public Object peek();
public void push(Object theObject);
public Object pop();
}
댓글 없음:
댓글 쓰기