java - 取链表Java的平均值
问题描述
public class Node {
...
public Node getNext() {...} // return next field
public int getData() {...} // returns data
}
假设变量 head 指向链表的第一个节点(即包含地址),编写语句以将链表的每个其他节点中的数据值打印到控制台。例如,如果列表有 5->4->3->2->1,则输出应该是 5 3 1 即只有中间有空格的数字。如果列表为空 0 大小),则您的代码不应打印任何内容。
您可以声明其他变量并假设列表可能有任意数量的节点,包括零。如果列表为空,则不打印任何内容,否则打印以空格分隔的数据。
我尝试了什么:
if (head == null) {
break;
}
else {
while (head != null) {
int current = head.getData();
System.out.print(current + " ");
head = head.getNext();
if (head == null) {
break;
}
head = head.getNext();
}
}
解决方案
创建一个指向链表头部的 Node 变量。然后您可以操作该变量并每隔一个节点传递一次,直到该变量为空,这意味着您已经遍历了整个链表。
if(head != null)
{
Node currentNode = head;
while(currentNode != null)
{
System.out.print(currentNode.getData());
if(currentNode.getNext()==null)
{
currentNode=null;
}
else
{
currentNode = currentNode.getNext().getNext();
}
}
}
while 循环中的 if 语句检查下一个节点是否不为空,这意味着不会出现 NullPointerException。
推荐阅读
- flutter - 颤振导航器不工作:OnPress 不显示第二个屏幕
- java - 通用置换函数元素比较给出编译器错误
- python - 数据框将文本拆分为新列
- serialization - F# 比较 lambda 是否相等
- google-apps-script - 谷歌表脚本权限给任何人
- swift - 在 AppKit 视图中嵌入 SwiftUI 视图
- android - 在自定义视图类中获取空指针
- javascript - TypeError:无法读取未定义的属性“地图”并四处走动
- javascript - HTML中可调整大小的弹性表
- sql - 在 SQL Server T-SQL 中创建“特定”形式的 XML,而不使用字符串连接