用链表模拟栈的代码实现

和数组的比较

链表容易报空指针异常的数据结构,但是它也有自己的好处,这里面不用判断栈是否已满,因为相对于数组来讲,链表是一种动态的存储方法,只需要在输出的时候判断是否为空即可

用链表模拟栈的代码实现

  • 进栈
  • 出栈
  • 遍历
  • 空栈
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 +
                '}';
    }
}



评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值