javaでスタックのpop,pushを行うためのプログラミングなのですが二つ作らないといけないのですがもう一つが思いつきません。
一つ目のスタックプログラミング
public class Main { public static void main(String[] args){ Stack stk = new Stack(); try{ stk.push("aaa"); stk.push("bbb"); stk.push("ccc"); stk.push("ddd"); }catch(Exception e){ System.out.println(e); } System.out.println(stk.isFull()); try{ System.out.println((String)stk.top()); }catch(Exception e){ System.out.println(e); } stk.show(); try{ System.out.println((String)stk.pop()); System.out.println((String)stk.pop()); System.out.println((String)stk.pop()); System.out.println((String)stk.pop()); }catch(Exception e){ System.out.println(e); } try{ System.out.println((String)stk.top()); }catch(Exception e){ System.out.println(e); } stk.show(); } }
public class Stack { private Cell head = new Cell(null); private Cell tail = head; private final int size = 3; private int pos = 0; void push(Object o)throws Exception{ if(isFull()){ throw new Exception("Stack Overflow"); } Cell idx = new Cell(o); tail.setNext(idx); tail = idx; ++pos; } Object pop() throws Exception{ if(isEmpty()){ throw new Exception("Stack Underflow"); } try{ return tail.getElement(); }finally{ Cell idx = head; for(; idx.getNext() != tail; idx = idx.getNext()); tail.setElement(null); tail.setNext(null); tail = idx; --pos; } } Object top() throws Exception{ if(isEmpty()){ throw new Exception("Stack is Empty"); } return tail.getElement(); } boolean isEmpty(){ return head == tail; } boolean isFull(){ return pos == size; } void show(){ if(isEmpty()){ System.out.println("スタックは空です"); return; } System.out.println(head.getNext()); } }
public class Cell { private Object element; private Cell next; Cell(Object element){ this.element = element; } public Object getElement(){ return element; } public Cell getNext(){ return next; } public void setElement(Object element){ this.element = element; } public void setNext(Cell next){ this.next = next; } public String toString(){ String s = (String)this.element; if(this.next == null){ return s; } else{ return (s+"<--"+(this.next).toString()); } } }
条件としてCellクラスを使用しないといけません
もう一つのスタックのやり方が思いつかないのでご教授お願いします。
あなたの回答
tips
プレビュー