栈
栈是先进后出
入栈:
public class zhan {
private int[] data = new int[5];
private int size = 0;
// size数组的长度(data的最后一个元素)
public void push(int x){//入栈
data[size++] = x;
if(size == data.length){
data = Arrays.copyOf(data,size*2);//数组的扩容
}
}
出栈:
public int pop(){//出栈
if(size == 0){
System.out.println("栈内为空");
return 0;
}
int result = data[size-1];
size--;
return result;
}
完整的栈代码实现
import java.util.Arrays;
public class zhan {
private int[] data = new int[5];
private int size = 0;
// size数组的长度(data的最后一个元素)
public void push(int x){//入栈
data[size++] = x;
if(size == data.length){
data = Arrays.copyOf(data,size*2);//数组的扩容
}
}
public int pop(){//出栈
if(size == 0){
System.out.println("栈内为空");
return 0;
}
int result = data[size-1];
size--;
return result;
}
}
测试类:
public class zhanTest {
public static void main(String[] args) {
zhan z = new zhan();
z.push(1);
z.push(2);
z.push(3);
z.push(4);
z.push(5);
z.push(6);
z.push(7);
System.out.println(z.pop());
System.out.println(z.pop());
System.out.println(z.pop());
System.out.println(z.pop());
System.out.println(z.pop());
System.out.println(z.pop());
System.out.println(z.pop());
System.out.println(z.pop());
}
}
按照 1 2 3 4 5 6 7的顺序的入栈,出栈的顺序是7 6 5 4 3 2 1
队列
队列是先进先出
入队列:
public void push(int x){
arr[size++] = x;
if (size>=arr.length){
arr = Arrays.copyOf(arr,size*2);
}
}
出队列:
public int pop(){
if (size == count){
System.out.println("队列为空");
}
int result = arr[count];
count++;
return result;
}
完整的队列代码实现
import java.util.Arrays;
public class duilie {
private int[] arr = new int[5];
private int size = 0;
public void push(int x){
arr[size++] = x;
if (size>=arr.length){
arr = Arrays.copyOf(arr,size*2);
}
}
private int count = 0;
public int pop(){
if (size == count){
System.out.println("队列为空");
}
int result = arr[count];
count++;
return result;
}
}
测试类:
public class duilieTest {
public static void main(String[] args) {
duilie d = new duilie();
d.push(1);
d.push(2);
d.push(3);
d.push(4);
d.push(5);
d.push(6);
d.push(7);
System.out.println(d.pop());
System.out.println(d.pop());
System.out.println(d.pop());
System.out.println(d.pop());
System.out.println(d.pop());
System.out.println(d.pop());
System.out.println(d.pop());
System.out.println(d.pop());
}
}
按照 1 2 3 4 5 6 7的顺序的入队列,出队列的顺序是1 2 3 4 5 6 7