数据结构里经常把堆栈和队列放一起,个人感觉堆栈和队列的实现方式难度差不多,仅当动手学习,参靠参考。
public class stackLinkList {
public static StackNode[] arr;
public static void main(String[] args) {
StackNode no = new StackNode("a");
StackNode no0 = new StackNode("b");
StackNode no1 = new StackNode("c");
arr = new StackNode[]{no,no0,no1};//用一个数组储存便于遍历结点
initStack(no);//初始化堆栈
push(no0);//进栈
push(no1);
showStack();//遍历堆栈
System.out.println("---------------------------");
pop();//出栈
showStack();//遍历堆栈
}
public static void pop(){
for (int i=0; i<arr.length; i++){
if (arr[i].isHead() == true){
arr[i].getNext().setHead(true);
arr[i]=null;
}
}
}
public static void initStack(StackNode stack){
stack.setHead(true);
stack.setNext(null);
}
public static void showStack(){
for (int i=0; i<arr.length; i++){
if(arr[i] != null){
arr[i].showStack();
} else {
System.out.println(arr[i]);
}
}
}
public static StackNode top(){
StackNode nn = new StackNode();
for (int i=0; i<arr.length; i++){
if (arr[i].isHead() == true){
nn=arr[i];
}
}
return nn;
}
public static void push(StackNode newStack){
newStack.setNext(top());
top().setHead(false);
newStack.setHead(true);
}
}
class StackNode<T>{
private T data;
private StackNode next;
private boolean isHead = false;
public StackNode() {
}
public StackNode(T data) {
this.data = data;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public StackNode getNext() {
return next;
}
public void setNext(StackNode next) {
this.next = next;
}
public boolean isHead() {
return isHead;
}
public void setHead(boolean head) {
isHead = head;
}
public void showStack() {
if(this.next == null){
System.out.println("stackNode{" +
"data=" + data +
", next=" + next +
",isHead=" + isHead +
'}');
} else {
System.out.println("stackNode{" +
"data=" + data +
", next=" + (next.getData() == null ? null : next.getData()) +
",isHead=" + isHead +
'}');
}
}
}
结果: