java-使用链表实现优先级队列
作者:互联网
我已经使用链表实现了优先级队列.在此优先级队列中,最小的int值具有最大值,因此,通过调用remove方法,将删除最小的方法.
节点类的代码
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方法是否是删除元素的最佳方法.所以我正在寻找建议.
解决方法:
remove()应该从列表中删除第一个元素,对吗?你为什么要为此循环呢?
由于您的列表是单链链接(仅指向Node中的下一个元素),因此您需要做的是:
>将第一个存储在临时变量中(如果它是!= null)
>然后先更新以指向列表中的第二项
(如果!= null,则为first.next)
>然后返回临时变量.
标签:data-structures,priority-queue,linked-list,java 来源: https://codeday.me/bug/20191121/2051114.html