2015-01-16 3 views
-1

연결된 목록에 노드를 추가하는 메서드를 만들려고합니다. 이 메소드는 String을 사용합니다. 이 방법은 내가 만든 방법입니다.add 메서드가 Java의 연결된 목록에서 작동하지 않습니다.

public void add(String x) 
    { 
     Node newNode = new Node(); 
     newNode.element = x; 
     newNode.nextNode = firstNode; 
     firstNode = newNode; 
    } 

불행히도이 코드는 작동하지 않습니다. 작동하도록 변경할 수있는 방법이 있습니까?

노드 내부 클래스와 링크 된 목록 클래스 :

class LinkedList implements StringCollection 
{ 
private static class Node 
{ 

    public String element; 
    public Node nextNode; 
    public Node (String element) 
    { 
    this.element = element; 
    this.nextNode = null; 
    } 

} 
private Node firstNode; 
public NodeStringCollection() 
{ 

    firstNode = null; 

} 

//add method goes here 

public String toString() 
{ 

    String s = ""; 
    Node node = firstNode; 
    while (node != null) 
    { 
    s = s + node.element + " "; 
    node = node.nextNode; 
    } 
    return s; 

} 
} 

링크 된 테스트 클래스 :

Class Test 
{ 
    public static void main(String [] args) 
    { 
    StringCollection sc = new LinkedList(); 
    sc.add (new String ("A")); 
    sc.add (new String ("B")); 
    sc.add (new String ("C")); 
    sc.add (new String ("D")); 
    System.out.println (sc); 
    int countStrings = sc.size(); 
    System.out.println (countStrings); 
    } 
} 
다음

내가 제공 한 모든 정보입니다

출력

D C B A 
4 
+1

첫째, 'String (String)'생성자를 호출하는 이유가 명확하지 않습니다. 다음으로, 새로운 노드를 추가한다는 점에서 코드가 작동하는 것처럼 보입니다. 그것은리스트의 * 앞쪽에 놓여 있습니다 - 그게 문제입니까? 출력은 어떤 방식으로 기대 한 것이 아닌가? –

+1

"불행히도,이 코드는 작동하지 않습니다."이것에 대해 자세히 설명해야합니다. 실제 문제는 무엇입니까? – JamesB

답변

0

코드가 수정되었습니다. 당신이 잘못한 것은 LinkedList에 추가 한 요소가 이전의 firstNode을 대체했다는 것입니다. 따라서 구현에 마지막으로 추가 한 노드가 새로운 첫 번째 노드가됩니다. 따라서 귀하의 LinkedListD C B A으로 인쇄되어야합니다.

아래 코드는 첫 번째 노드와 마지막 노드를 저장합니다. 새 노드가 추가되면, 우리는 새로 만든 노드의 마지막 노드 점을하자 다음 새로 만든 노드의 마지막 노드 설정 :

코드를

public class LinkedList { 
    public static class Node { 
     public String element; 
     public Node nextNode; 

     public Node(String element) { 
      this.element = element; 
      this.nextNode = null; 
     } 

    } 

    private Node firstNode; 
    private Node lastNode; 

    public LinkedList() { 
     firstNode = null; 
     lastNode = null; 
    } 

    public void add(String x) { 
     Node newNode = new Node(x); 

     if (firstNode == null) 
      firstNode = newNode; 
     if (lastNode != null) 
      lastNode.nextNode = newNode; 
     lastNode = newNode; 
    } 

    public String toString() { 
     String s = ""; 
     Node node = firstNode; 
     while (node != null) { 
      s = s + node.element + " "; 
      node = node.nextNode; 
     } 
     return s; 
    } 
} 

예제 코드

public static void main(String args[]) throws Exception { 
    LinkedList sc = new LinkedList(); 
    sc.add(new String("A")); 
    sc.add(new String("B")); 
    sc.add(new String("C")); 
    sc.add(new String("D")); 
    System.out.println(sc); 
} 

출력

A B C D 
관련 문제