1

文字の配列があり、各文字を次のノードにリンクするノードに変換しようとしています。問題は、私が無限ループに陥り続けていることであり、その理由がわかりません。これが私のコードです:

String map = "ABBACBCCA";
char[] charArray = map.toCharArray();
ListNode head;
ListNode temp;
ListNode next;

for (int i = 0; i < charArray.length - 1; i++) {
     temp = new ListNode(charArray[i]);
     next = new ListNode(charArray[i+1]);
     temp.next = next;

     if (i == 0) {
          head = temp;
     }
}

ListNode クラスは次のようになります。

class ListNode<T> {
     public T data = null;
     public ListNode next = null;

     public ListNode(T data) {
          this.data = data;
     }
}

for ループの最後の反復に達した後、無限ループに陥ったようです。理由は誰にもわかりますか?

4

4 に答える 4

1

まず、あなたが望むと思います:

next = new ListNode(charArray[i]);

することが

next = new ListNode(charArray[i+1]);

私が気づいた他の何か:

for (int i = 0; i < charArray.length - 1; i++) {
     temp = new ListNode(charArray[i]);
     next = new ListNode(charArray[i+1]);
     temp.next = next;

          if (i == 0) {
            head = temp;
           }
     }

私はこれがあなたが望むものをもたらすとは思わない. それはあなたにA-> B-> B-> Aなどを与えません。それ以上に-> A-> B、B-> Bなどを与えるでしょう。それがあなたが求めているものかどうかはわかりません。

さらに、これでうまくいくと思います:

String map = "ABBACBCCA";
        ListNode<Character> head = null;
        ListNode<Character> newHead = null;
        ListNode<Character> next = null;

        char[] charArray = map.toCharArray();

        head = newHead = new ListNode<Character>(charArray[0]);
        for (int i = 1; i < charArray.length - 1; i++) {
            next = new ListNode<Character>(charArray[i]);

            newHead.next = next;

            newHead = next;
        }

基本的に作成してリンクして作成してリンクします。(私にとってはうまくテストされました)醜い着信!

System.out.println(head.data);
        ListNode<Character> nextptr = head.next;
        while (true) {

            if (nextptr.next == null) {
                break;
            }
            System.out.println(nextptr.data);
            nextptr = nextptr.next;
        }
于 2013-10-23T03:43:47.700 に答える
0

参照変数 temp と next は、各反復中に新しいオブジェクトに割り当てられ、次のポインターを追跡できなくなります。他の人が示唆したように、デバッガーを使用してこの問題を理解できたはずです。これが実際の例です。

public class Test {

    public static void main(String args[]) {
        String map = "ABBACBCCA";
        char[] charArray = map.toCharArray();
        ListNode<Character> head = null, temp = null;
        for (int i = 0; i < charArray.length; i++) {
            ListNode<Character> obj = new ListNode<Character>(charArray[i]);
            if (temp != null) {
                temp.next = obj;
            } else {
                head = obj;
            }
            temp = obj;
        }
        // Print the list
        while (head != null) {
             System.out.println(head.data);
             head = head.next;
        }
    }
}

class ListNode<T> {
    public T data = null;
    public ListNode<T> next;
    public ListNode(T data) {
        this.data = data;
        this.next = null;
    }
}
于 2013-10-23T06:58:53.080 に答える