一、Queuejava
隊列, 一種經常使用的數據結構,能夠將隊列看作是一種特殊的線性表,該結構遵循的先進先出原則。Java中,LinkedList實現了Queue接口,由於LinkedList進行插入、刪除操做效率較高
相關方法:
boolean offer(E e):將元素追加到隊列末尾,若添加成功則返回true。
E poll():從隊首刪除並返回該元素。
E peek():返回隊首元素,可是不刪除
示例:數據結構
public class QueueDemo { public static void main(String [] args) { Queue<String> queue = new LinkedList<String>(); //追加元素 queue.offer("one"); queue.offer("two"); queue.offer("three"); queue.offer("four"); System.out.println(queue); //從隊首取出元素並刪除 String poll = queue.poll(); System.out.println(poll); System.out.println(queue); //從隊首取出元素可是不刪除 String peek = queue.peek(); System.out.println(peek); System.out.println(queue); //遍歷隊列,這裏要注意,每次取完元素後都會刪除,整個 //隊列會變短,因此只須要判斷隊列的大小便可 while(queue.size() > 0) { System.out.println(queue.poll()); } } }
運行結果:
[one, two, three, four]
one
[two, three, four]
two
[two, three, four]
two
three
fourcode
二、Deque接口
雙向隊列,指該隊列兩端的元素既能入隊(offer)也能出隊(poll),若是將Deque限制爲只能從一端入隊和出隊,則可實現棧的數據結構。對於棧而言,有入棧(push)和出棧(pop),遵循先進後出原則three
經常使用方法以下:
void push(E e):將給定元素」壓入」棧中。存入的元素會在棧首。即:棧的第一個元素
E pop():將棧首元素刪除並返回。
示例:隊列
public class DequeDemo { public static void main(String[] args) { Deque<String> deque = new LinkedList<String>(); deque.push("a"); deque.push("b"); deque.push("c"); System.out.println(deque); //獲取棧首元素後,元素不會出棧 String str = deque.peek(); System.out.println(str); System.out.println(deque); while(deque.size() > 0) { //獲取棧首元素後,元素將會出棧 System.out.println(deque.pop()); } System.out.println(deque); } }
運行結果:
[c, b, a]
c
[c, b, a]
c
b
a
[]class