1 前言
使用单向链表也可以实现栈,通过在链表的表头插入的方式实现push操作,删除链表的表头结点(栈顶结点)实现pop操作。具体push操作和单向链表在链表头部添加结点的方法类似,具体pop操作和单向链表在链表头部删除结点的方法类似。大家忘记的话,可以看看我之前的文章《单向链表的基本操作: java语言实现》。
2 基于单向链表的方法实现栈
2.1 创建结点类
package Stack_Study;
/**
* Created by Administrator on 2018/5/13.
*/
public class LLNode {
private int data; //数据域
private LLNode next; //指针域
public LLNode(int data) {
this.data = data;
this.next = null;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public LLNode getNext() {
return next;
}
public void setNext(LLNode next) {
this.next = next;
}
}
2.2 创建栈类
package Stack_Study; /** * Created by Administrator on 2018/5/13. */ public class LLStack { private LLNode top; private int length = 0; public LLStack() { this.top = null; } //判断栈中是否有元素 public boolean isEmpty() { if(top == null) { return true; }else { return false; } } //入栈:将数据压入栈 public void push(int data) { LLNode newNode = new LLNode(data); if(isEmpty()) { top = newNode; }else { newNode.setNext(top); top = newNode; } length++; } //出栈:删除并返回最后一个插入栈的元素 public int pop() { if(isEmpty()) { System.out.println("栈为空"); return 0; }else { int data = top.getData(); top = top.getNext(); length--; return data; } } //获取栈顶的元素,但不出栈 public int top() { if(isEmpty()) { System.out.println("栈为空"); return 0; }else { return top.getData(); } } //返回栈中元素的个数 public int size() { return length; } //删除栈 public void deteleStack() { top = null; } }
3 建立测试类
测试类建立如下,运行结果这里不再赘述。
package Stack_Study;
/**
* Created by Administrator on 2018/5/13.
*/
public class LLStackTest {
public static void main(String[] args) {
LLStack stack = new LLStack();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
System.out.println(stack.pop());
System.out.println(stack.top());
System.out.println(stack.size());
System.out.println(stack.isEmpty());
}
}
4 参考资料
[1] 数据结构与算法经典问题解析