简体   繁体   中英

java linked list .This program does not print 8.Why?

Singly linked list.

  1. I create node
  2. add new node

Implementation:

//create node
class Node {
  int data;
  Node next;

  Node(int data) {
    this.data = data;
    next = null;
  }
}
public class LinkedList {

  //Add new node
  public static void add(Node root, int data){
    Node temp;
    while (root != null) {
      root = root.next;
    }
    temp = new Node(data);
    root = temp;
  }
  //print node
  public static void print(Node root){
    while (root != null) {
      System.out.println(root.data);
      root = root.next;
    }
  }

  public static void main(String[] args) {
    Node root ;
    Node iter;
    root = new Node(7);
    iter = root;
    add(iter, 8);
    print(iter);
  }

}

I work data structures. I want to linked list but the program is failing. this program does not print 8.Why?

Where am I making mistakes?

while(root!=null){
   root=root.next;
}
 temp=new Node(data);
 root=temp;

Here : root is NULL at a time. After the loop, you don't assign at the last element of the chain a next element. You don't perform anything in your chain because root points to a NULL value and doesn't refer to an element of your chain.
Besides, it has no sense to assign a value to a method parameter since it is not taken into consideration when the method exits.

If you want to add the Node at the end of the node chain, you should replace the code by :

while(root.next !=null){
   root=root.next;
}
temp=new Node(data);
root.next=temp;

You could write with more meaningful names :

Node lastElement = root;
while(lastElement.next !=null){
   lastElement=lastElement.next;
}
temp=new Node(data);
lastElement.next=temp;

Anyway, a more simple solution would be to have a field in your class which store the last Node of the chain. Iterating over all the elements to add a element at the end is not very efficient.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM