java - 为什么 node.next 去下一个节点
问题描述
我是编程新手,目前正在处理链表。我在网上的某个地方得到了这个代码。
public class Node
{
Node next;
int data;
public Node(int data)
{
this.data=data;
}
public class LinkedList
{
Node head;
public void delete(int data)
{
Node current=head;
while (current.next!=null)
{
if (current.next.data==data)
{
current.next= current.next.next;
}
}
}
}
}
我不明白的是为什么node.next
指向下一个节点?在 Node 类中,下一个是数据类型 Node。Node 类中没有 next 方法,但在调用LinkedList
该类时current.next
,它假定引用下一个节点。
解决方案
Consider thie code here every node i added in the main method is one object of the class Node and this class contains Node next which is a reference to the next node. For example the first node with value 22
contains a reference to the second node with value 2
. For example if you have only one node added the Node next will refer to null because there is no second node. In every node object the Node next reference gives you the next node. But i strongly suggest you to read what is reference in java because you miss a fundamental concepts here.
import java.util.Objects;
class LinkedList<T> {
private class Node<E> {
Node<E> next;
E val;
Node(E val) {
this.val = val;
}
}
private Node<T> head;
void add(T val) {
Node<T> node = new Node<>(val);
if (head == null) {
head = node;
} else {
Node<T> p = head;
while (p.next != null) {
p = p.next;
}
p.next = node;
}
}
void show() {
if (head == null)
return;
Node<T> p = Objects.requireNonNull(head);
while (p.next != null) {
System.out.print(p.val + " ");
p = p.next;
}
System.out.println(p.val);
}
}
class Main {
public static void main(String... args) {
LinkedList<Integer> ll = new LinkedList<>();
ll.add(22);
ll.add(2);
ll.add(4);
ll.add(32);
ll.add(3);
ll.add(1);
ll.add(44);
ll.show();
}
}
推荐阅读
- edx - 为什么在 edX 安装中调用 api/user/v1/accounts 端点并不总是提供姓名和电子邮件地址?
- amazon-web-services - AWS-ECS-Task 完成任务后如何停止它?
- c# - 用逗号拆分正则表达式匹配的字符串?
- nginx - [nginx-config]:使用 'location' 替换部分 url
- oracle-apex - 在 Select2 多值选择列表中重新选择项目
- javascript - 是的验证模式同步与异步验证并显示一个字段的多个错误
- r - 在 r data.table 中查找重复组
- r - R中并行计算中的临时对象
- c++ - 如何在函数中使用二维数组?
- java - 如何获取 EditText 以检查它是否等于 Integer ArrayList 中的任何数字?