首页 > 解决方案 > 取链表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();
                }
            }

标签: java

解决方案


创建一个指向链表头部的 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。


推荐阅读