在head为null的链表中插入

时间:2017-11-21 15:25:37

标签: java nodes singly-linked-list

我有节点类

class Node{
  int data;
  Node next;
}

我必须将节点插入列表。 它工作正常。但总是头值为零。

public void createlist(Node n,int p)
{  
    Node newone = new Node();
    newone.data=p;
    newone.next=null;
    if(n==null)
      n=newone;
    else
    {
        while(temp.next!=null)
         temp=temp.next;
        temp.next=newone;
    }
}

在main函数中,我创建了头节点

 public static void main(String args[] ) {

    Scanner s = new Scanner(System.in);
    Node head=new Node();
    createlist(head,5);
 }

创建此实现后,从头部开始的列表如下所示  0→5。为什么0来了?。

1 个答案:

答案 0 :(得分:1)

Zero来自head节点本身:

Node head=new Node();

永远不会被createList方法修改,因此默认值为零仍保留在data字段中。

归结为无法通过在以下代码中分配head来更改main内的n

if(n==null)
    n=newone;

这就是为什么你被迫在new Node内创建main,所以事实上n是 永远不会null

您可以通过多种方式解决此问题:

  • 以特殊方式处理头节点 - 忽略head节点的打印,删除等,或
  • 更改对Node个对象进行操作的方法以返回修改后的列表 - 这样可以插入新节点或删除头节点,或者
  • 介绍拥有所有节点的MyList - 移动"伞上的所有列表操作" class,并在那里处理head节点。