- java 數據結構 列和棧的實現
- 棧的原理 先進後出 先進入的放在最下面後進入的在最上面,拿的時候從最上面拿 這就是棧的原理
代碼如下:
public class MyStack {
//底層實現是一個數組
private long[] arr;
private int top;//表示棧頂
/**
* 默認的構造方法
*/
public MyStack() {
arr = new long[10];
top = -1;
}
/**
* 帶參數構造方法,參數爲數組初始化大小
*/
public MyStack(int maxsize) {
arr = new long[maxsize];
top = -1;
}
/**
* 添加數據
*/
public void push(int value) {
arr[++top] = value;
}
/**
* 移除數據
*/
public long pop() {
return arr[top--];
}
/**
* 查看數據
*/
public long peek() {
return arr[top];
}
/**
* 判斷是否爲空
*/
public boolean isEmpty() {
return top == -1;
}
/**
* 判斷是否滿了
*/
public boolean isFull() {
return top == arr.length - 1;
}
}
測試代碼:
public static void main(String[] args) {
MyStack ms = new MyStack(4);
ms.push(23);
ms.push(12);
ms.push(1);
ms.push(90);
System.out.println(ms.isEmpty());
System.out.println(ms.isFull());
System.out.println(ms.peek());
while(!ms.isEmpty()) {
System.out.print(ms.pop() + ",");
}
System.out.println();
System.out.println(ms.isEmpty());
System.out.println(ms.isFull());
}
隊列的原理:先進先出,後進後出 ,就比如你去火車站買票,第一人排隊的肯定是他先買完走了。排在最後的肯定是最後走
代碼如下:
/*
* 列隊類
*/
public class MyCycleQueue {
//底層使用數組
private long[] arr;
//有效數據的大小
private int elements;
//隊頭
private int front;
//隊尾
private int end;
/**
* 默認構造方法
*/
public MyCycleQueue() {
arr = new long[10];
elements = 0;
front = 0;
end = -1;
}
/**
* 帶參數的構造方法,參數爲數組的大小
*/
public MyCycleQueue(int maxsize) {
arr = new long[maxsize];
elements = 0;
front = 0;
end = -1;
}
/**
* 添加數據,從隊尾插入
*/
public void insert(long value) {
if(end == arr.length - 1) {// 如果添加的數據滿了。就重新開始添加讓end=-1
end = -1;
}
arr[++end] = value;
elements++;
}
/**
* 刪除數據,從隊頭刪除
*/
public long remove() {
long value = arr[front++];//每次取一個數據
if(front == arr.length) {//如果front 的值等於arr.length 說明取完了從新開始
front = 0;
}
elements--;
return value;
}
/**
* 查看數據,從隊頭查看
*/
public long peek() {
return arr[front];
}
/**
* 判斷是否爲空
*/
public boolean isEmpty() {
return elements == 0;
}
/**
* 判斷是否滿了
*/
public boolean isFull() {
return elements == arr.length;
}
}
測試代碼:
public static void main(String[] args) {
MyCycleQueue mq = new MyCycleQueue(4);
mq.insert(23);
mq.insert(45);
mq.insert(13);
mq.insert(1);
System.out.println(mq.isFull());
System.out.println(mq.isEmpty());
System.out.println(mq.peek());
System.out.println(mq.peek());
while (!mq.isEmpty()) {
System.out.print(mq.remove() + " ");
}
System.out.println();
mq.insert(23);
mq.insert(45);
mq.insert(13);
mq.insert(1);
while (!mq.isEmpty()) {
System.out.print(mq.remove() + " ");
}
}
數據結構總是那麼難。今天先寫倆個比較簡單的,後續我還會繼續發表博客,第一寫會有不對的地方還請大家多多指教。