前言
我們生活中會遇見很多的看起來很棘手的問題,比如一堆尚未處理的郵件,正要去電影院排隊購買一張電影票(兩張也可以,你值得擁有...),這些我們用自己熟悉的方式來處理他們,而我們自己熟悉的這些方式,很可能就和棧和隊列有關.今天,我們就來談談棧和隊列.
棧的定義
棧是限定僅在表尾進行插入和刪除操作的線性表,也稱爲LIFO(後入先出)結構.
我們把允許插入和刪除的地方稱之爲棧頂,另一端稱之爲棧底,,不包含任何元素稱之爲空棧
棧可以用順序結構和鏈式結構表示,本例爲了方便描述問題,用順序結構.
棧的插入操作我們稱之爲入棧(push),棧的刪除操作我們稱之爲出棧(pop)
順序棧的Java代碼實現
5.public class Statck<E extends Object> {
6. private List<E> pool = new ArrayList<E>();
7.
8. public Statck() {
9. }
10.
11. public void clear() {
12. pool.clear();
13. }
14.
15. public boolean isEmpty() {
16. return pool.isEmpty();
17. }
18.
19. /**
20. * 獲取棧頂元素
21. * */
22. public E getTopObjcet() {
23. if (isEmpty()) {return null;}
24. return pool.get(0);
25. }
26.
27. /**
28. * 彈出棧操作
29. * */
30. public E pop() {
31. if (isEmpty()) {throw new EmptyStackException();}
32. return pool.remove(pool.size() - 1);
33. }
34.
35. /**
36. * 壓入棧
37. * */
38. public void push(E e) {
39. if (isEmpty()) {throw new EmptyStackException();}
40. pool.add(e);
41. }
42.
43. /**
44. * 獲取當前棧大小
45. * */
46. public int getStatckSize() {
47. if (isEmpty()) {throw new EmptyStackException();}
48. return pool.size();
49. }
50.
51.}
隊列的定義
隊列是隻允許在一端插入,在另一端刪除的線性表
允許插入的那一端稱之爲隊尾,允許刪除的那一端稱之爲隊頭,是FIFO(先入先出)結構
隊列有順序結構和鏈式結構,一般來說,順序結構刪除操作是o(N)的性能,而鏈式結構只有o(1);
順序隊列的Java代碼實現
class Queue //隊列類
{
private int maxSize; //隊列長度,由構造函數初始化
private long[] queArray; // 隊列
private int front; //隊頭
private int rear; //隊尾
private int nItems; //元素的個數
public Queue(int s) // 構造函數
{
maxSize = s;
queArray = new long[maxSize];
front = 0;
rear = -1;
nItems = 0;
}
public void insert(long j) // 進隊列
{
if(rear == maxSize-1) // 處理循環
rear = -1;
queArray[++rear] = j; // 隊尾指針加1,把值j加入隊尾
nItems++;
}
public long remove() // 取得隊列的隊頭元素。
{
long temp = queArray[front++]; // 取值和修改隊頭指針
if(front == maxSize) // 處理循環
front = 0;
nItems--;
return temp;
}
public long peekFront() // 取得隊列的隊頭元素。該運算與 remove()不同,後者要修改隊頭元素指針。
{
return queArray[front];
}
public boolean isEmpty() // 判隊列是否爲空。若爲空返回一個真值,否則返回一個假值。
{
return (nItems==0);
}
public boolean isFull() // 判隊列是否已滿。若已滿返回一個真值,否則返回一個假值。
{
return (nItems==maxSize);
}
public int size() // 返回隊列的長度
{
return nItems;
}
}
public class IntegerQueue
{
public static void main(String[] args)
{
Queue theQueue = new Queue(5); // 隊列有5個元素
theQueue.insert(10); // 添加4個元素
theQueue.insert(20);
theQueue.insert(30);
theQueue.remove(); // 移除3個元素
theQueue.insert(60);
theQueue.insert(70);
theQueue.insert(80);
while( !theQueue.isEmpty() ) // 遍歷隊列並移除所有元素
{
long n = theQueue.remove(); // (40, 50, 60, 70, 80)
System.out.print(n);
System.out.print(" ");
}
System.out.println("");
}
}