[英]Need guidance on creating Node class (java)?
我需要实现一个Node类,其中的基本方法是:getItem()、getNext()、setItem()和setNext()。 我希望节点至少能够将 Java 中的默认整数范围存储为“项目”; “下一个”应该是链接列表中下一个节点的引用或指针,或者如果这是列表中的最后一个节点,则为特殊的节点 NIL。我还想实现一个双参数构造函数,它使用给定的初始化实例项目(第一个参数)和下一个节点(第二个参数),我有点撞墙了,需要一些关于实现这个的指导,有什么想法吗?
到目前为止我有这个:
class Node {
public Node(Object o, Node n) {
}
public static final Node NIL = new Node(Node.NIL, Node.NIL);
public Object getItem() {
return null;
}
public Node getNext() {
return null;
}
public void setItem(Object o) {
}
public void setNext(Node n) {
}
}
我可以给你一个关于如何做到这一点的快速提示:
Class Node{
//these are private class attributes, you need getter and setter to alter them.
private int item;
private Node nextNode;
//this is a constructor with a parameter
public Node(int item)
{
this.item = item;
this.nextNode = null;
}
// a setter for your item
public void setItem(int newItem)
{
this.item = newItem;
}
// this is a getter for your item
public int getItem()
{
return this.item;
}
}
您可以通过调用创建一个 Node 对象:
Node newNode = Node(2);
这不是您问题的完整解决方案,缺少两个参数构造函数和最后一个节点链接,但这应该会引导您走向正确的方向。
下面是 Node 实现的一个简单示例,(为了便于阅读,我将 Item 重命名为 Value)。 它必须以某种方式实现,因为方法签名似乎是强加给您的。 但请记住,这绝对不是实现 LinkedList 的最佳方式。
public class Node {
public static final Node NIL = null;
private Integer value;
private Integer next;
public Node(Integer value, Node next) {
this.value = value;
this.next = next;
}
public Integer getValue() {
return this.value;
}
public Node getNext() {
return this.next;
}
public void setValue(Integer value) {
this.value = value;
}
public void setNext(Node next) {
this.next = next;
}
public boolean isLastNode() {
return this.next == Node.NIL || Node;
}
}
public class App {
public static void main(String[] args) {
Node lastNode = new Node(92, Node.NIL);
Node secondNode = new Node(64, lastNode);
Node firstNode = new Node(42, secondNode);
Node iterator = firstNode;
do () {
System.out.println("node value : " + iterator.getValue());
iterator = iterator.getNext();
} while (iterator == null || !iterator.isLastNode());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.