我看了几个网上的实现,不太满意,所以在重新复习的时候,顺便把它们再实现一遍
- 链栈
/**
* @author Obj9527
*
*/
public class LinkedStack{
LNode<Object> head = null;//头节点
/*
* 内部类用来定义单链表节点
*/
private class LNode<T>{
T data;
public LNode<T> next;
public LNode(T data) {
this.data = data;
}
@Override
public String toString() {
return data.toString();
}
}
public LinkedStack(Object data) {
head = new LNode<Object>(data);
}
/*
* 用头插法入栈实现LIFO,链栈采用的是非连续内存区域,
* 不需要考虑栈满,除非物理内存爆了
*/
public void push(Object data) {
LNode<Object> node = new LNode<Object>(data);
node.next = head.next;
head.next = node;
}
/*
* Java不能手动指定销毁对象,所以这里不用管freeNode,
* 让Java垃圾回收器自己处理,出栈需要考虑栈空,所以需要
* 进行空栈判断
*/
public Object pop() {
if (head.next == null) {
throw new RuntimeException("The Stack is empty");
}
LNode<Object> freeNode = head.next;
head.next = freeNode.next;
return freeNode.data;
}
}
- 顺序栈
/**
* @author Obj9527
*
*/
public class ArrayStack{
private int data[] = null;//数据域
private int top = -1;//指针
public ArrayStack(int maxSize) {
data = new int[maxSize];
}
/*
* 入栈
*/
public void push(int num) {
if (top == data.length-1) {
throw new RuntimeException("stack is full");
}
data[(++top)] = num;
}
/*
* 出栈
*/
public int pop() {
if (isEmpty()) {
throw new RuntimeException("stack is empty");
}
return data[(top--)];
}
/*
* 判断栈空
*/
public boolean isEmpty() {
if (top == -1) {
return true;
}
return false;
}
}
- 顺序队
/**
* @author Obj9527
*
*/
public class ArrayQuene {
int data[] = null;//数据域
int front = 0;//头指针
int rear = 0;//尾指针
/*
* 创建时赋予队列大小
*/
public ArrayQuene(int maxSize) {
data = new int[maxSize];
}
/*
* 入队
*/
public void enQuene(int value) {
if ((rear+1) % this.data.length == front) {
throw new RuntimeException("The Quene is full");
}
rear = (rear+1) % this.data.length;
data[rear] = value;
}
/*
* 出队
*/
public int deQuene() {
if (front == rear) {
throw new RuntimeException("The Quene is empty");
}
front = (front + 1) % this.data.length;
return data[front];
}
}
- 链队
/**
* @author Obj9527
*
*/
public class LinkedQuene {
private QNode<Object> front = new QNode<Object>("head");//头指针
private QNode<Object> rear = front;//尾指针
/*
* 队节点
*/
class QNode<T>{
T data;
QNode<T> next;
public QNode(T value) {
this.data = value;
}
@Override
public String toString() {
return this.data.toString();
}
}
/*
* 入队
*/
public void enQuene(Object value) {
QNode<Object> qNode = new QNode<Object>(value);
rear.next = qNode;
rear = qNode;
}
/*
* 出队
*/
public Object deQuene() {
if (front == rear) {
throw new RuntimeException("The Quene is empty!");
}
front = front.next;
return front.data;
}
}