使用链接列表实现优先级队列

编程入门 行业动态 更新时间:2024-10-08 14:41:59
本文介绍了使用链接列表实现优先级队列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我使用链表实现了优先级队列。在此优先级队列中,最小的int值具有最高值,因此通过调用remove方法将删除最小的方法。

I have implemented a priority queue using a linked list. In this priority queue the smallest int value has the highest value and therefore by calling the remove method the smallest method will be removed.

节点类的代码

public class Node { public int iData; public Node next; public Node(int x) { iData = x; } public void displayNode() { System.out.println(iData + " "); } }

链接列表代码

public class LinkList { private Node first; public LinkList() { first = null; } public boolean isEmpty() { return first == null; } public void insert(int x) { Node newNode = new Node(x); Node previous = null; Node current = first; while (current != null && x < current.iData) { previous = current; current = current.next; } if (previous == null) { newNode.next = first; first = newNode; } else { previous.next = newNode; newNode.next = current; } } public Node remove() { Node previous = null; Node current = first; Node temp = current; while (current.next != null) { previous = current; current = current.next; } previous.next = null; return temp; } public void display() { Node current = first; while (current != null) { current.displayNode(); current = current.next; } System.out.println(" "); } }

优先级队列代码

public class PriorityQ { private LinkList list; public PriorityQ() { list = new LinkList(); } public void insert(int x) { list.insert(x); } public void remove() { list.remove(); } public void displayList() { System.out.println("Largest Value to Smallest"); list.display(); } }

目前工作正常,但是我不确定链接列表类中的remove方法是否是删除元素的最佳方法。所以我正在寻找建议。

It is working fine at the moment, however i am not sure if my remove method in the link list class is the best way to go about removing elements. So i am looking for suggestions.

推荐答案

remove()应该是假设从列表中删除第一个元素,对吧?为什么要为此循环任何东西?

remove() is supposed to remove the first element from the list, right? Why do you loop anything for that?

由于您的列表是单链接的(仅指向节点中的下一个元素),您需要做的只是:

Since your list is singly-linked (only pointing to next elements in the Node) all you need to do is:

  • 将第一个存储在临时变量中(如果它是!= null)

  • Store the first in a temporary variable (if it's != null)

    然后更新首先指向列表中的第二项( first.next if!= null)

    Then update first to be pointing to the 2nd item in the list (first.next if != null)

    然后返回临时变量。

  • 更多推荐

    使用链接列表实现优先级队列

    本文发布于:2023-11-29 06:08:38,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1645560.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:优先级   队列   链接   列表

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!