gpt4 book ai didi

java - 当我在节点对象内传递 "top"的 Node 变量时?它有助于它指向以前的数据吗?

转载 作者:太空宇宙 更新时间:2023-11-04 10:38:00 25 4
gpt4 key购买 nike

我正在编写一段代码来练习一些基础知识的链表示例,但在 voidadd 方法的链表类中遇到问题,当我传递节点对象内“顶部”的 Node 变量时,这意味着什么?它有助于它指向以前的数据吗?我已经指出了涉及我的问题的部分

public class Node
{
private int data;
private Node nextNode;

public Node(int dataP , Node nextNodeP)
{
data = dataP;nextNode = nextNodeP;
}

public int getData()
{
return data;
}

public Node getNextNode()
{
return nextNode;
}

public void setData(int newData) //to replace the value of some notes [12| ] --> [120| ]
{
data = newData;
}


public void setNext(Node newNextNode) // pointing to top ---> [120| ] ---> [last | null]
{
nextNode = newNextNode;
}
}

public class LinkedList {
private Node top;
private int size;

public LinkedList() {
top = null;
size = 0;
}

public int getSize() {
return size;
}

public void addNode(int newData) {
Node temp = new Node(newData, top); //question
top = temp; //points to the same
size++;
}
}

最佳答案

在其自己的类中定义一个节点。这是一个简单的例子:

public class LinkedList {

private Node first,last;
private int size ;

//adds node as last. not null safe
public void addNode(Node node) {

if(first == null) {
node.setParent(null);
first = node;
last = node;
}else {
node.setParent(last);
last = node;
}

size++;
}

public Node getFirst() {return first;}
public Node getLast() { return last; }
public int getSize() {return size;}

public static void main(String[] args) {

LinkedList list = new LinkedList();
list.addNode(new Node(0,null));
list.addNode(new Node(1,null));
list.addNode(new Node(2,null));
list.addNode(new Node(3,null));

Node node = list.getLast();
System.out.println("list has "+ list.size + " nodes:");
while(node != null) {
System.out.println(node);
node = node.getParent();
}
}
}

class Node{

private int data;
private Node parent;
Node(int nodeData, Node parent) {
data = nodeData;
this.parent = parent;
}

public int getData() { return data;}
public void setData(int data) { this.data = data; }
public Node getParent() {return parent; }
public void setParent(Node parent) {this.parent = parent;}
@Override
public String toString() {return "Node "+getData() +" parent:"+ getParent();}
}

关于java - 当我在节点对象内传递 "top"的 Node 变量时?它有助于它指向以前的数据吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49290828/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com