棧和佇列的簡單例項
阿新 • • 發佈:2018-12-23
棧
import java.util.Stack;
public class StackClass {
public static void main(String[] args) {
Stack s=new Stack();
s.push("A");
s.push("B");
s.push("C");
s.push("D");
s.push("E");
System.out.println("壓棧資料:");
System.out.println (s);
System.out.println("==============");
System.out.println("出棧資料:");
System.out.print(s.pop()+" ");
System.out.print(s.pop()+" ");
System.out.print(s.pop()+" ");
System.out.print(s.pop()+" ");
System.out.print(s.pop()+" ");
}
}
結果
佇列
import java.util.LinkedList;
import java.util.Queue;
public class QueueClass {
public static void main(String[] args) {
Queue<String> qu=new LinkedList<String>() ;
System.out.println("新增資料:");
qu.offer("A");
qu.offer("B");
qu.offer ("C");
qu.offer("D");
qu.offer("E");
for (String string : qu) {
System.out.print(string+" ");
}
System.out.println();
System.out.println("移除資料:");
System.out.print(qu.poll()+" ");
System.out.print(qu.poll()+" ");
System.out.print(qu.poll()+" ");
System.out.print(qu.poll()+" ");
System.out.print(qu.poll()+" ");
}
}
結果