For example lets run it like this How many nodes enter 2, so now my list is q.data= 2 which points to the next node which has a value 5, points to next value 6. At this point node Q. next equals null
DisplayList prints out 2 5 6.
That means Q is pointing to the head, How did that occur. And what makes Q.next change in DisplayList.
enter code hereimport java.util.*; // to import the class Scanner
import java.io.*;
public class BuildList{
public static void main(String[] args ){
node q = new node (0,null );
q.buildmyList(q);
q.DisplayList(q);
}
}
class node
{
int data;
node next;
public node()
{data = 0; next = null;}
public node(int x, node n)
{data = x; next =n;}
public void buildmyList(node q)
{//node q = new node(0,null);
node head = q;
String oneLine;
try{BufferedReader indata = new
BufferedReader(new InputStreamReader(System.in));
System.out.println("How many nodes?\n");
oneLine = indata.readLine();
head.data = Integer.parseInt(oneLine);
for (int i=1; i<=head.data; i++)
{System.out.println("A new value please\n");
oneLine = indata.readLine();
int num = Integer.parseInt(oneLine);
node p = new node(num,null);
q.next = p;
q = p;
//System.out.println("q = p qdata" + q.data );
}
}catch(Exception e)
{ System.out.println("Error --" + e.toString());}
}
public void DisplayList(node q)
{if (q != null)
{ System.out.println(q.data);
DisplayList(q.next);
}
}
}
Aucun commentaire:
Enregistrer un commentaire