创建节点:
class StackNode {private StackNode next;private int no;public StackNode getNext() {return next;}public void setNext(StackNode next) {this.next = next;}public StackNode(int no) {this.no = no;}public int getNo() {return no;}public void setNo(int no) {this.no = no;}@Overridepublic String toString() {return "StackNode{" + "no =" + no +'}';}
}
创建单链表:
class SingleLinkedStack {private StackNode head = new StackNode(0);private int maxsize;public SingleLinkedStack(int maxsize) {this.maxsize = maxsize;}//判断栈中总共有多少元素public int size() {StackNode temp = head.getNext();if (isEmpty()) {return 0;}int length = 1;while (temp.getNext() != null) {length++;temp = temp.getNext();}return length;}//判断是否栈空public boolean isEmpty() {return head.getNext() == null;}//判断是否栈满public boolean isFull() {return maxsize == size();}//入栈操作public void push(StackNode newNode) {StackNode temp = head; //将临时指针指向头节点if (isFull()) {System.out.println("栈满,不能继续添加元素");return;}while (temp.getNext() != null) {temp = temp.getNext();}System.out.printf("元素 %d 入栈\n", newNode.getNo());temp.setNext(newNode);}//出栈操作public void pop() {StackNode temp = head; //将临时指针指向头节点StackNode next = head.getNext(); //将临时指针指向第一个元素System.out.println("元素出栈操作...");if (isEmpty()) {System.out.println("栈空,无可用元素出栈");return;}while (next.getNext() != null) {//将两个指针同步向后移动temp = temp.getNext();next = next.getNext();}System.out.printf("元素 %d 出栈\n", next.getNo());temp.setNext(null);}//打印栈元素public void StackShow() {StackNode temp = head.getNext(); //将临时指针指向第一个元素System.out.println("======栈元素打印(入栈顺序)=====");if (isEmpty()) {System.out.println("栈空,无可用元素打印");}while (temp != null) {System.out.printf("元素 %d \n", temp.getNo());temp = temp.getNext();}}//逆序打印栈中元素public void reverseShow1() {Stack<StackNode> stackTemp = new Stack<StackNode>();if (isEmpty()) {System.out.println("栈空,无元素打印~");}StackNode temp = head.getNext();System.out.println("======逆序输出栈元素======");while (temp != null) {stackTemp.push(temp);temp = temp.getNext();}while (stackTemp.size() > 0) {System.out.printf("元素 %d \n", stackTemp.pop().getNo());}}}
测试:
public class ArrayStackDemo3 {public static void main(String[] args) {//测试SingleLinkedStack stack = new SingleLinkedStack(4);//创建新节点StackNode node1 = new StackNode(1);StackNode node2 = new StackNode(2);StackNode node3 = new StackNode(3);StackNode node4 = new StackNode(4);StackNode node5 = new StackNode(5);//入栈stack.push(node1);stack.push(node2);stack.push(node3);stack.push(node4);stack.push(node5);//打印元素stack.StackShow();//逆向打印栈元素stack.reverseShow1();
// stack.reverseShow2();//出栈stack.pop();stack.pop();stack.pop();stack.pop();stack.pop();}
}
控制台输出:
相关文章:使用数组实现栈的相关操作
使用双向链表实现栈的相关操作