顺序栈和顺序队列、循环队列

1.对顺序栈的各种操作
import java.util.Arrays;
import java.util.EmptyStackException;
import java.util.Random;
class SeqStack{
// 存储栈元素的数组
private int[] stack;
// 标识栈顶的位置
private int top;
// 默认构造,初始大小为10
public SeqStack() {
this(10);
}
// 用户指定栈的初始大小
public SeqStack(int size) {
this.stack=new int[size];
this.top=0;
}
// 入栈操作
public void push(int val){
if(this.topthis.stack.length) {
this.stack = Arrays.copyOf(this.stack, this.stack.length * 2);
}
this.stack[this.top++]=val;
}
// 出栈,并把出栈的元素返回
public int pop(){
–this.top;
int val=this.stack[top];
return val;
}
// 返回栈顶元素
public int top(){
return stack[this.top-1];
}
// 判断栈空
public boolean empty(){
return this.top
0;
}
// 判断栈满
public boolean full(){
return stack.lengththis.top;
}
// 返回栈元素的个数
public int size(){
return this.top;
}
// 自定义栈元素的打印方式
public String toString() {
String str = new String();
for (int i = 0; i < this.top; i++) {
str = str + this.stack[i] + " ";
}
return str;
}
}
//顺序栈代码测试
public class SeqStackTest {
public static void main(String[] args) {
Random rd = new Random();
SeqStack Stack=new SeqStack(10);
for (int i = 0; i < 20; i++) {
Stack.push(i+1);
}
Stack.push(10);
System.out.println(Stack);
Stack.pop();
System.out.println(Stack);
}
}
2.对顺序队列几循环换队列的各种操作
import java.util.Arrays;
class Queue{
// 存储队列的元素
private int[] queue;
// 队头
private int front;
// 队尾
private int rear;
// 15
public Queue() {
this(15);
}
// 自定义队列大小
public Queue(int size) {
this.queue=new int[size];
this.front=0;
this.rear=0;
}
// 入队操作,循环队列
public void offer(int val){
if(full()){
this.queue =Arrays.copyOf(this.queue,this.queue.length *2);
}
this.queue[this.rear]=val;
this.rear=(this.rear+1)%this.queue.length;
}
//入队操作
public void offer1(int val){
if(full()){
this.queue =Arrays.copyOf(this.queue,this.queue.length *2);
}
this.queue[this.rear++]=val;
}
// 出队,并把队头元素返回,循环队列
public int poll(){
int val=this.queue[this.front];
this.front=(this.front+1)%this.queue.length;
return val;
}
//出队,并把对头元素返回
public int poll1(){
int val=this.queue[this.front];
this.front++;
return val;
}
// 查看队头元素
public int peek(){
return this.queue[this.front];
}
//判断队满,循环队列
public boolean full1(){
return this.rear
queue.length-1;
}
//判断队满
public boolean full(){
return this.rearqueue.length;
}
//判断队空
public boolean empty1(){
return this.rear
this.front;
}
// 判断队空,循环队列
public boolean empty(){
this.rear=(this.rear+1)%this.queue.length;
return this.rear==this.front;
}
}
public class QueueTestUnit {
public static void main(String[] args) {
Queue queue=new Queue(15);
queue.offer1(10);
queue.offer(10);
System.out.println(queue);
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值