基礎算法和數據結構合集:
https://blog.csdn.net/GD_ONE/article/details/104061907
摘要
之前已經介紹過JAVA中已經實現好的棧和隊列,本文主要介紹如何用數組模擬棧和隊列。用數組模擬棧和隊列的的優點就是快。
棧
棧的特點是“先進後出”,只能在棧頂進行插入和刪除,所以用數組模擬的話,我們只能在數組的末尾進行插入和刪除。
代碼很簡單,一看就能明白:
public class Main{
static int[] s = new int[100010]; // 棧
static int idx = 0; // 表示棧內有多少個元素,並指向棧頂
public static void push(int x){ // 插入元素
s[idx++] = x;
}
public static void pop(){ // 刪除棧頂元素
idx --;
}
public static int peek(){//獲取棧頂元素
return s[idx-1]; //注意這裏是idx-1
}
public static Boolean isEmpty(){ // 判空
if(idx == 0) return true;
else return false;
}
public static void main(String[] args){
}
}
隊列
隊列的特點是“先進先出”,只能在隊頭刪除,隊尾插入。
和棧不同的是我們需要兩個指針,一個指向隊頭,一個指向隊尾。
public class Main{
static int[] Q = new int[100010]; // 隊列
static int l = 0, r = 0; //隊頭和隊尾
public static void push(int x){ // 入隊
Q[r++] = x;
}
public static void pop(){ // 出隊
l++;
}
public static int peek(){//獲取隊頭元素
return Q[l];
}
public static Boolean isEmpty(){ // 判空
if(r - l == 0) return true;
else return false;
}
public static void main(String[] args){
}
}