2014-10-08 2 views
0

Я изучаю связанные списки. С некоторой помощью из книги Cracking the Coding Interview я создал следующий код для создания связанных списков, добавления элементов в конец и печати элементов. Однако, когда я запускаю код, он возвращает только «нуль» вместо печати списка i.e. «Sanchez». «Ozil» и «Welbeck». Помогите?Java - Перемещение только связанного списка возвращает null

public class CreateLinkedList{ 

    static class Node{ 
     String PlayerName; 
     Node next = null; 

     //Constructor 
     Node(String PName){ 
      PlayerName = PName; 
     } 

     //Method to insert a Node 
     void InsertNodeAtEnd(String PlayerName){ 
      Node transition = new Node(PlayerName); 
      Node n = this; 
      while(n.next != null){ 
       n = n.next; 
       } 
      n.next = transition;    
      }  

     //Method to print all elements of linked list 
     void PrintList(){ 
      Node n = this; 
      while (n.next != null){ 
       System.out.println(n.PlayerName + "\n"); 
       n = n.next; 
      } 
     } 
    } 

    public static void main(String[] args) { 

     Node first = new Node("Sanchez"); 
     first.InsertNodeAtEnd("Ozil"); 
     first.InsertNodeAtEnd("Welbeck"); 
     first.PrintList(); 
    } 
} 
+0

Я просто побежал ваш код, как это в настоящее время, и я получил '' Sanchez' и Ozil', как выход (по-прежнему не хватает одного, но увидеть ответ @Debasish Яны за что). Где вы получаете нуль? – Fodder

+0

Я только что нашел что-то не так с моим затмением. Странно, что я знаю. Пробовал в netbeans и работал нормально – satnam

ответ

2
public class CreateLinkedList { 
static class Node { 
    String PlayerName; 
    Node next = null; 

    // Constructor 
    Node(String PName) { 
     PlayerName = PName; 
    } 

    // Method to insert a Node 
    void InsertNodeAtEnd(String PlayerName) { 
     Node transition = new Node(PlayerName); 
     Node n = this; 
     while (n.next != null) { 
      n = n.next; 
     } 
     n.next = transition; 
    } 

    // Method to print all elements of linked list 
    void PrintList() { 
     Node n = this; 
     while (n != null) { 
      System.out.println(n.PlayerName + "\n"); 
      n = n.next; 
     } 
    } 
} 

public static void main(String[] args) { 

    Node first = new Node("Sanchez"); 
    first.InsertNodeAtEnd("Ozil"); 
    first.InsertNodeAtEnd("Welbeck"); 
    first.PrintList(); 
} 
} 

ВЫВОД

Sanchez 

Ozil 

Welbeck 
0

В перечне печати итерации для каждого элемента, последняя итерация не хватали, поэтому я изменил условие

void PrintList(){ 
       Node n = this; 
       while (n != null){ 
        System.out.println(n.PlayerName + "\n"); 
        n = n.next; 
       } 
      } 
0

петли Я довольно уверен, Проблема заключается в том, что вы добавляете в связанный список.

Node n = this; 

это указывает на сам класс, который не является узлом.
Вы должны реализовать переменную Node в классе, который представляет первый узел. Так что-то вроде этого:

public class CreateLinkedList{ 


static class Node{ 
    //all this stuff seemed fine 
    } 

Node first = null;//represents first item 

    //Method to insert a Node 
    void InsertNodeAtEnd(String PlayerName){ 
     Node transition = new Node(PlayerName); 
     Node n = first; 
     if(n!=null){ 
      while(n.next != null){ 
       n = n.next; 
       } 
      n.next = transition;    
     } 
     else 
     first = transition; 



    //Method to print all elements of linked list 
    void PrintList(){ 
     Node n = first; 
     while (n.next != null){ 
      System.out.println(n.PlayerName + "\n"); 
      n = n.next; 
     } 
    } 
} 

public static void main(String[] args) { 

    Node first = new Node("Sanchez"); 
    first.InsertNodeAtEnd("Ozil"); 
    first.InsertNodeAtEnd("Welbeck"); 
    first.PrintList(); 
} 
}' 
0

В перечень печати в то время как итерация используют следующее в качестве условия проверки:

п = нуль

вместо

н .next! = null

В вашем коде цикл пропускает последнюю итерацию, когда вы сравниваете следующий узел вместо текущего узла.

Правильный метод:

//Method to print all elements of linked list 
void PrintList(){ 
    Node n = this; 
    while (n != null){ 
     System.out.println(n.PlayerName + "\n"); 
     n = n.next; 
    } 
}