-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
첫째, 'String (String)'생성자를 호출하는 이유가 명확하지 않습니다. 다음으로, 새로운 노드를 추가한다는 점에서 코드가 작동하는 것처럼 보입니다. 그것은리스트의 * 앞쪽에 놓여 있습니다 - 그게 문제입니까? 출력은 어떤 방식으로 기대 한 것이 아닌가? –
"불행히도,이 코드는 작동하지 않습니다."이것에 대해 자세히 설명해야합니다. 실제 문제는 무엇입니까? – JamesB