栈的描述:
线性结构,有序列表,先进后出
数组实现栈:
思路:记录一下栈顶元素的索引,加入新元素时索引++,索引位置对应的值设为新元素,直到栈满,取出元素后,索引–,直到小于0,栈空;
/**
* 链表实现栈
*/
public class ArrayStack {
/**
* 栈顶
*/
private int top = -1;
/**
* 栈最大长度
*/
private int maxSize;
/**
* 封装数据的数组
*/
private int[] arr;
/**
* 初始化方法
*
* @param maxSize
*/
public ArrayStack(int maxSize) {
this.maxSize = maxSize;
arr = new int[maxSize];
}
/**
* 栈满
*
* @return
*/
public boolean isFull() {
return top == maxSize - 1;
}
/**
* 是否为空
*
* @return
*/
public boolean isEmpty() {
return top < 0;
}
/**
* 入栈
*
* @param add
*/
public void push(int add) {
if (isFull()) {
System.out.println("栈满");
return;
}
top++;
arr[top] = add;
}
/**
* 出栈
*/
public int poll() {
if (isEmpty()) {
System.out.println("栈空");
return -1;
}
int value = arr[top];
top--;
return value;
}
/**
* 查看栈顶
*
* @return
*/
public int peek() {
if (isEmpty()) {
System.out.println("栈空");
return -1;
}
return arr[top];
}
public void show() {
while (top >=0) {
System.out.println(poll());
}
}
public void showArray() {
System.out.println(Arrays.toString(arr));
}
}
单链表实现栈:
思路:将新加的节点放在head节点的下一个位置,取出的时候直接取head节点的下一个节点,直到链表为空
/**
* 链表实现栈
*/
public class LinkedStack {
private Node head = new Node();
public LinkedStack() {
}
/**
* 是否为空
*
* @return
*/
public boolean isEmpty() {
return head.next == null;
}
/**
* 入栈
*
* @param node
*/
public void push(Node node) {
node.next = head.next;
head.next = node;
}
/**
* 出栈
*/
public Node poll() {
if (isEmpty()) {
System.out.println("栈空");
return null;
}
Node next = head.next;
head.next = next.next;
return next;
}
/**
* 查看栈顶
*
* @return
*/
public Node peek() {
if (isEmpty()) {
System.out.println("栈空");
return null;
}
return head.next;
}
public void show() {
if (isEmpty()) {
System.out.println("栈空");
return;
}
Node next = head.next;
while (next != null) {
System.out.println("出栈" + next);
head.next = next.next;
next = head.next;
}
System.out.println("出栈完毕");
}
public void showArray() {
if (isEmpty()) {
System.out.println("栈空");
return;
}
Node next = head.next;
while (next != null) {
System.out.println("遍历" + next);
next = next.next;
}
System.out.println("遍历完毕");
}
public static class Node {
public String value;
public Node next;
public Node() {
}
public Node(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
@Override
public String toString() {
return "Node{" +
"value='" + value + '\'' +
'}';
}
}
}