数据结构入门之用链表模拟栈

1:栈的介绍:

  • LIFO(last in first out)表示就是后进入的元素, 第一个弹出栈空间.往往先把拿出去使用.
  • 其限制是仅允许在表的一端进行插入和删除运算。这一端被称为栈顶,相对地,把另一端称为栈底。
  • 向一个栈插入新元素又称作进栈、入栈或压栈,它是把新元素放到栈顶元素的上面,使之成为新的栈顶元素;
  • 从一个栈删除元素又称作出栈或退栈,它是把栈顶元素删除掉,使其相邻的元素成为新的栈顶元素。

2:实现代码:

链表定义:

//模拟链表
class Node {
    //个数
    public int no;
    //节点
    public Node next;

    public Node(int no) {
        this.no = no;
    }

    public Node(int no, Node next) {
        this.no = no;
        this.next = next;
    }
}

栈定义:

/**
 * 用链表模拟栈
 */
public class StackDemo {
    //栈的大小
    int maxSize;
    Node header;//栈顶元素
    int noCount;//栈内元素个数

    //初始化
    public StackDemo(int maxSize) {
        this.maxSize = maxSize;
        header = null;
        noCount = 0;
    }

    //判断栈满
    public boolean isEop() {
        if (maxSize == noCount) {
            return true;
        }
        return false;
    }

    //判断栈是否有值
    public boolean isEmpt() {
        if (noCount == 0) {
            return true;
        }
        return false;
    }

    //入栈
    public void push(int node) {
        if (isEop()) {
            System.out.println("栈满");
            return;
        }
        //注意这里面试将原来的header作为参数传入,然后以新new出来的Node作为header
        header = new Node(node, header);//node是数据,header是下一个节点
        noCount++;//个数加一
    }

    //出栈
    public int pop() {
        if (isEmpt()) {
            throw new RuntimeException("栈空");
        }
        //获取数据
        int no = header.no;
        //移向下个节点
        header = header.next;
        noCount--;
        return no;
    }

    //遍历
    public void list() {
        if (isEmpt()) {
            System.out.println("没有数据");
            return;
        }
        Node temp = header;//辅助节点 遍历用
        while (true) {
            if (temp == null) {
                break;
            }
            System.out.println(temp.no);
            //下移
            temp = temp.next;
        }
    }
}

因为在备考学校,数据结构入门基本会形成全套的代码实现

posted @ 2021-08-27 12:14  小杰i  阅读(123)  评论(0编辑  收藏  举报