和数组的比较
链表容易报空指针异常的数据结构,但是它也有自己的好处,这里面不用判断栈是否已满,因为相对于数组来讲,链表是一种动态的存储方法,只需要在输出的时候判断是否为空即可
用链表模拟栈的代码实现
- 进栈
- 出栈
- 遍历
- 空栈
package com.hhit.stack;
//使用链表模拟栈
public class LinklistStackDemo {
public static void main(String[] args) {
//测试类
Stack2 stack2 = new Stack2();
stack2.push(1);
stack2.push(2);
stack2.push(3);
stack2.push(4);
stack2.list();
System.out.println("出栈:");
System.out.println(stack2.pop());
System.out.println(stack2.pop());
System.out.println(stack2.pop());
System.out.println(stack2.pop());
}
}
class Stack2 {
//链表实现不需要考虑是否为满的情况,因为是链式的,根据计算机空间而定
//定义一个头节点
Node head = new Node(0);
//临时变量,保存头节点
Node temp = head;
//判断是否为空
public boolean isEmpty() {
return head.next == null;
}
//进栈
public void push(int value) {
Node node =new Node(value);
temp.next=node;
temp=temp.next;
}
//出栈
public int pop() {
if(isEmpty()){
System.out.println("栈为空");
return -1;
}
Node pre=head;
while (true){
if(pre.next==temp){
break;
}
pre=pre.next;
}
pre.next=temp.next;
int value=temp.no;
temp=pre;
return value;
}
//遍历栈
public void list() {
temp=head;
if(isEmpty()){
System.out.println("栈空");
return;
}
while(true){
if (temp.next==null){
break;
}
System.out.println(temp.next.no);
temp=temp.next;
}
}
}
//在这个类里面定义节点
class Node {
int no;
Node next;
public Node(int no) {
this.no = no;
}
@Override
public String toString() {
return "Node{" +
"no=" + no +
'}';
}
}