栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

一个通过链表构造队列的好问题

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

一个通过链表构造队列的好问题

通过链表构造队列是一个算法基本功。而很多基本功,不一定是算法的,还可能是java基础的。我们一起来看一下问题。之前我一段代码是这么写的:

public class linkQueue {
    private Node front;
    private Node rear;
    private int size;

    public linkQueue() {
        this.front = new Node(0);
        this.rear = new Node(0);
    }

    
    public void push(int value) {
        Node newNode = new Node(value);
        Node temp = front;
        while (temp.next != null) {
            temp = temp.next;
        }
        temp.next = newNode;

 
        size++;
    }

    
    public int pull() {
        if (front.next == null) {
            System.out.println("队列已空");
        }
        Node firstNode = front.next;
        front.next = firstNode.next;
        size--;
        return firstNode.data;
    }

    
    public void traverse() {
        Node temp = front.next;
        while (temp != null) {
            System.out.print(temp.data + "t");
            temp = temp.next;
        }
    }

    static class Node {
        public int data;
        public Node next;

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

然后再写个测试类:

    public static void main(String[] args) {

        linkQueue topic12linkQueue = new linkQueue();
        topic12linkQueue.push(1);
        topic12linkQueue.push(2);
        topic12linkQueue.push(3);
//        System.out.println("第一个出队的元素为:" + topic12linkQueue.pull());
        System.out.println("队列中的元素为:");
        topic12linkQueue.traverse();
    }

这时候执行并没有什么问题,但是有个同学对push有疑问:既然有rear和font了,那为什么不直接让rear指向新结点,而font还是要遍历一遍呢?也就是为什么不能这么写:

    public void push(int value) {
        Node newNode = new Node(value);
        rear.next = newNode;
        rear = newNode;
        size++;
    }

如果调试一下,你会发现链表的size是对的,但是rear和font不正常,为什么呢?因为这里的font和rear是没有关联的,是两个独立变化的链表,构造函数没有将其关联起来,后面push和pull的时候是只操作了rear和font,这就导致两个链表一直都没有关联到一起。

如果要解决,可以在构造方法里这么写:

 this.rear = front;

然后push方法就可以这么写了。

构造方法和push的完整代码:

    public linkQueue() {
        this.front = new Node(0);
        //一个很巧妙的设计
        this.rear = front;
    }

    
    public void push(int value) {
        Node newNode = new Node(value);
        rear.next = newNode;
        rear = newNode;
        size++;
    }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/458952.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号