我正在编写一个程序,我必须创建一个充满节点的双链表,用户可以使用自己的值插入这些节点。我有方法将新节点插入到列表的不同部分(前面、位置、尾部) 。每个节点有两个信息,一个String和一个order INT(两者都是用户在创建新节点后设置的。 我的问题是如何将第一个信息设置为字符串(在我给出的示例中,有带有机器人元素 INT 的版本,但第一个信息必须是字符串,这就是我需要帮助的地方)
public void insertInFirstPosition(int information,int key) {
Node n = new Node(information,key, null, null);
if (head == null) {
n.setLinkNext(n);
n.setLinkPrev(n);
head = n;
tail = head;
} else {
n.setLinkPrev(tail);
tail.setLinkNext(n);
head.setLinkPrev(n);
n.setLinkNext(head);
head = n;
}
size++;
}
这是节点类` 公共(public)类节点{
private int data;
private int informazione;
private Node next, prev;
/* Constructor */
public Node() {
next = null;
prev = null;
data = 0;
informazione = 0;
}
public Node(int i,int k, Node n, Node p) {
data = i;
informazione = k;
next = n;
prev = p;
}
/* Function to set link to next node */
public void setLinkNext (Node n) {
next = n;
}
/* Function to set link to previous node */
public void setLinkPrev(Node p) {
prev = p;
}
/* Funtion to get link to next node */
public Node getNext() {
return next;
}
/* Function to get link to previous node */
public Node getPrev() {
return prev;
}
/* Function to set information to node */
public void setInformazione(int i) {
informazione = i;
}
/* Function to get data from node */
public int getInformazione() {
return informazione;
}
/* Function to set data to node */
public void setData(int d) {
data = d;
}
/* Function to get data from node */
public int getData() {
return data;
}
}`
在此代码中,您只能为两个节点槽输入 INT 值,第二个槽可以,必须是 int,同时第一个槽必须是 String。 感谢大家的帮助。
最佳答案
您应该使您的 Node
类通用,并让它接受任何类作为数据。
class Node<T> {
T data;
Node<T> prev;
Node<T> next;
public Node (T data, Node<T> prev, Node<T> next) {
this.data = data;
this.prev = prev;
this.next = next;
}
}
现在您可以定义一个类(我们称之为 SomeClass
),其中包含要存储在给定 Node
中的所有属性,并创建一个 Node
与:
Node<SomeClass> n = new Node<SomeClass>(new SomeClass(information,key), null, null);
关于java - 如何设置具有两个信息的 TREE NODE<T> - [STRING.INT]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44674684/