我们用链表的形式来模拟栈的数据结构
分析:
1.入栈:可以链表节点的添加看作入栈的过程
2.出栈:我们从栈中每取出一个数据,就拿到链表的尾部的值并从将尾部的节点删除
3.显示栈中所有数据:链表反转输出
代码实现
1.定义节点
class Node {
public int value;
public Node next;
public Node(int value) {
this.value = value;
}
}
2.定义栈
class LinkedListStack {
private Node head = new Node(0);
}
3.入栈(push)
//向栈中放入数据
public void push(Node node) {
Node top = head;
while (top.next != null) {
top = top.next;
}
top.next = node;
}
4.出栈(pop)获取链表的尾部的值并从将尾部的节点删除
public int pop() throws Exception {
Node pre=head;
Node top = head.next;
if (top==null){
throw new Exception("栈空,无法取出数据");
}
while (top.next!=null){
top=top.next;
pre=pre.next;
}
int value=top.value;
pre.next=null;
return value;
}
}
出栈图解(字丑请多担待!)
显示栈中所有数据(链表反转输出)
//先将单向链表原地反转
public void show() {
Node temp = head.next.next;
if (head.next == null) {
System.out.println("栈空,无法显示");
}
head.next.next=null;
while (temp != null) {
Node cur=temp.next;
temp.next=head.next;
head.next=temp;
temp=cur;
}
//循环遍历输出值
temp= head.next;
while (temp!=null){
System.out.println(temp.value);
temp=temp.next;
}
}