1、源码
Player实体类
package com.study.stack;public class Player {private Player next;private int no;public Player(int no) {this.no = no;}public Player getNext() {return next;}public void setNext(Player next) {this.next = next;}public int getNo() {return no;}public void setNo(int no) {this.no = no;}@Overridepublic String toString() {return "Player{" +"no=" + no +'}';}}
SingleLinkedStack类
package com.study.stack;import java.util.Stack;public class SingleLinkedStack {private Player player = new Player(0);private Player temp = player;//栈空public boolean isEmpty(){return player.getNext()==null;}//入栈public void push(int value){Player node = new Player(value);temp.setNext(node);temp = temp.getNext();}//出栈public void pop(){if (isEmpty()){System.out.println("栈空");return;}Player cur = player;while (true){if (cur.getNext()==temp){break;}cur = cur.getNext();}cur.setNext(temp.getNext());int value = temp.getNo();temp = cur;System.out.println(value);}//显示栈public void list() {temp = player;if (isEmpty()) {System.out.println("栈空");return;}while (true) {if (temp.getNext() == null) {break;}System.out.println(temp.getNext());temp = temp.getNext();}}}
SingleLinkedStackDemo测试类
package com.study.stack;public class SingleLinkedStackDemo {public static void main(String[] args) {SingleLinkedStack stack = new SingleLinkedStack();stack.push(1);stack.push(2);stack.push(3);stack.push(4);stack.push(5);stack.pop();stack.pop();stack.pop();stack.list();}}
测试结果
因为链表本身是动态的,所以并不需要像数组一样设置栈的大小
