# 栈与队列理解

## 👇 栈的实现（顺序表实现）

### 👉判断栈是否为空

public class Mystack {
private int[] array = new int[50];
private int size = 0;
//判断是否为空
public boolean isEmpty(){
return size==0;
}
}


### 👉 返回栈的长度

public class Mystack {
private int[] array = new int[50];
private int size = 0;
public int size(){
return size;
}
}


### ✨进栈

public class Mystack {
private int[] array = new int[50];
private int size = 0;
//进栈
public void push(int val){
array[size]=val;
size++;
}
}


### ✨出栈

public class Mystack {
private int[] array = new int[50];
private int size = 0;
//出栈
public int  pop(){
if (!isEmpty()){
int temp = array[size];
size--;
return temp;
}else {
throw new RuntimeException("空栈");
}
}
}


### ⭐️获取栈顶元素

public class Mystack {
private int[] array = new int[50];
private int size = 0;
//获取栈顶元素
public int peek(){
if (!isEmpty()){
return array[size-1];
}else{
throw new RuntimeException("空栈");
}
}
}


## 👇 队列的实现(链表实现)

### ✨入队列

class node{
public node next;
public int val;
public node(int val){
this.val=val;
}
}
public class Myqueue {
private node tail;
private int size;
//判断是否为空
public boolean isEmpty(){
return size == 0;
}
//获取队列的长度
public int size(){
return size;
}
//入队列
public void enquene(int val){
node cur = new node(val);
}else{
tail.next=cur;
}
tail=cur;
size++;
}
}


### ✨出队列

    //出队列
public int dequene(){
if (size==0){
throw new RuntimeException("空队列");
}
tail=null;//如果头结点为空，那么尾节点也是不能有任何指向的
}
size--;
}


### ⭐️获取队列头元素

 //获取队列头元素
public int peek(){
if (size==0){
throw new RuntimeException("空队列");
}
}


|
2天前
|

11 3
|
2天前
|

10 3
|
2天前

4 0
|
2天前

7 1
|
7天前
|

11 0
|
7天前
|

14 2
|
7天前
|

13 0
|
7天前
|

8 0
|
7天前
|

9 0
|
7天前
|

4 0