栈与队列
栈与队列都是比较基础的数据结构
栈
栈的特点是先进后出,他的底层是由数组实现的
我们来做一个简单的栈的封装
class MyStack{
int[] data;
int top = 0 ;
public MyStack(int size){
this.data = new int[size];
}
//放入的方法
public void push(int val) throws Exception {
//有一种情况无法再放入了
if (top == this.data.length){
throw new Exception("满了");
}
data[top] = val;
top++;
}
//取出的方法
public int pop() throws Exception {
if (top == 0){
throw new Exception("空的");
}
top--;
return data[top];
}
//判断是否为空的方法
public boolean isEmpty(){
if (top == 0)return true;
else return false;
}
}
队列
队列的特点是先进先出,他的底层是由链表实现
我们来封装一个简单的队列
class MyQueue{
Node head = null;//永远指向第一个值
Node tail = null;//永远指向最后一个值
int maxsize;
int size ;
public MyQueue(int maxsize){
this.maxsize= maxsize;
this.size = 0;
}
public void push(int val){
Node node = new Node(val);
if (size == 0){
head = node;
tail = node;
}else {
tail.next = node;
tail = node;
}
size++;
}
public int pop() throws Exception{
if (size == 0){
throw new Exception("空的");
}
int result = head.val;
head = head.next;
size--;
return result;
}
}
用栈实现队列
如何用栈来实现队列呢?
用一个栈不是不能实现队列的,所有我们用两个栈,一个栈用来存放数据,另一个栈用来做容器。
在第一个栈中先后放入C,B,A三个对象,队列的特点是先进先出,所以为了获取C,我们要先将A放入第二个栈中,再将B放入第二个栈中,再将C放入第二个栈,取出C后,把B和A还原回栈1。队列push的时候是加在栈1,pop的时候是栈2出栈。
以下是代码实现
用上面简单封装的栈来实现
class MyQueneWithStack{
MyStack myStack1;
MyStack myStack2;
public MyQueneWithStack(int size){
myStack1 = new MyStack(size);
myStack2 = new MyStack(size);
}
public void push(int val) throws Exception {
myStack1.push(val);
}
public int pop() throws Exception {
while (!myStack1.isEmpty()){
myStack2.push(myStack1.pop());
}
int result = myStack2.pop();
while (!myStack1.isEmpty()){
myStack1.push(myStack2.pop());
}
return result;
}
}