Stack简介
栈:一种特殊的线性表,其只允许在固定的一端进行插入和删除元素操作。进行数据插入和删除操作的一端称为栈顶,另一端称为栈底。栈中的数据元素遵守后进先出LIFO(Last In First Out)的原则。
栈的实现
package MyStack;
import java.util.Arrays;
public class MyStack {
public int[] elem;
public int usedSize;
public MyStack(){
this.elem = new int[10];
}
public void push(int data) {
if (isFull()){
elem = Arrays.copyOf(elem,2*elem.length);
}
elem[usedSize] = data;
usedSize++;
} //压栈
public boolean isFull() {
return usedSize == elem.length;
} //判满
public int pop() {
if(isEmpty()){
throw new StackEmptyExecption("空");
}
int val = elem[usedSize-1];
usedSize--;
return val;
}
public int peek(){
if(isEmpty()){
throw new StackEmptyExecption("空");
}
int val = elem[usedSize-1];
return val;
}
public boolean isEmpty(){
return usedSize == 0;
}
}
队列简介
在Java中,Queue是个接口,底层是通过链表实现的。遵循先入先出的原则
单行链表队列实现
package MyQueue;
//单链表队列的实现
public class MyQueue {
static class Node{
public int val;
public Node next;
public Node(int val){
this.val = val;
}
}
public Node head;
public Node last;
public int usedSize = 0;
public void offer(int val){
Node node = new Node(val);
if(head == null){
head = node;
last = node;
} else {
last.next = node;
last = node;
}
usedSize++;
}
public int poll(){
if(empty()){
return -1;
}
int ret = head.val;
head = head.next;
usedSize--;
return ret;
}
public int peek(){
if(empty()){
return -1;
}
return head.val;
}
public int getUsedSize(){
return usedSize;
}
public boolean empty() {
return usedSize == 0;
}
}
循环队列的实现
package MyCycleQueue;
//循环队列的实现
public class MyCycleQueue {
private int[] elem;
private int front;
private int rear;
public MyCycleQueue(int k){
this.elem = new int[k];
}
public boolean enQueue(int value){
if(isFull()){
return false;
}
elem[rear] = value;
rear = (rear + 1) % elem.length;
return true;
}
public boolean deQueue(){
if(isEmpty()){
return false;
}
front = (front+1)%elem.length;
return true;
}
public int Front(){
if(isEmpty()){
return -1;
}
return elem[front];
}
public int Rear(){
if(isEmpty()){
return -1;
}
int index = (rear == 0) ? elem.length-1 : rear-1;
return elem[index];
}
public boolean isEmpty(){
return front == rear;
}
public boolean isFull(){
return (rear+1)%elem.length == front;
}
}