我需要将Node类中包含的一些对象插入到已排序的LinkedList类中。 Node类看起来像:
public class Node {
private Card val;
private Node next;
public Node(Card v) {
val = v;
next = null;
}
其中card实现了Comparator接口。我正在尝试编写一个函数来按照LinkedList类中的卡值以排序顺序(从低到高)插入这些卡(不是java.util.LinkedList类,而是我正在编写的链表类)。有人知道我怎么做吗?它也不能是一个双重链表。
答案 0 :(得分:1)
我认为你所看到的就像我下面提到的那样(注意我没有编译,但它应该给你一个想法,希望对你有所帮助)
public class Node {
private Card val;
private Node next;
public Node(Card v) {
val = v;
next = null;
}
public Card getVal() { return val; }
oublic void setVal(Card v) { val = v; }
public Node getNext() { return next; }
public void setNext(Node n) { next = n; }
}
public class MyLinkList {
private Node head = null;
public void addNode(Card v) {
if (head == null) {
head = new Node(v);
} else {
Node last = null;
for (Node node = head; node != null && node.getVal().compareTo(v) < 0 ; ) {
last = node;
node = node.next;
}
Node newNode = new Node(v);
last.setNext(newNode);
newNode.setNext(node);
}
}
}
答案 1 :(得分:0)
我试过这个代码..它有点乱,但可以帮助你..
public static void main(String[] args) {
Card[] cards = { new Card(10), new Card(5), new Card(34), new Card(2)};
Node node = new Node(new Card(1));
Node firstNode = node;
Node tran = firstNode;
for (Card c : cards) {
Node newNode = new Node(c);
int a=0;
do {
if(a==1) {
tran = tran.getNode();
}
if ((tran.getCard().compareTo(c) == -1)) {
if (tran.getNode() == null) {
tran.setNode(newNode);
firstNode = node;
break;
} else if (tran.getNode() != null && ran.getNode().getCard().compareTo(c) == +1) {
newNode.setNode(tran.getNode());
node.setNode(newNode);
firstNode = node;
break;
}
} else if ((tran.getCard().compareTo(c) == +1)) {
newNode.setNode(tran.getNode());
firstNode = newNode;
break;
} else if(tran.getCard().compareTo(c) == 0){
newNode.setNode(tran.getNode());
firstNode = newNode;
break;
}
a=1;
} while (tran.getNode() != null);
tran = firstNode;
}
Node traversalNode = firstNode;
while (traversalNode.getNode() != null) {
System.out.println(traversalNode.getCard());
traversalNode = traversalNode.getNode();
}
}