字符串到单链列表

问题描述

我正在尝试将字符串转换为链表,其中每个数字都位于单独的节点中。

我尝试调试它,但是似乎找不到逻辑上的问题。 我在每个节点上总是得到一个奇怪的2位数字,甚至不一定出现在字符串中的数字。

请注意ListNode是我用来创建新节点对象的类。

String number = "807";
   
int size = number.length();
int pos = 0;
ListNode dummyhead = new ListNode();
ListNode curr = dummyhead;
while (size > 0){
    curr.next = new ListNode(number.charat(pos));   
    pos++;
    size--;
    curr = curr.next;
}

return dummyhead.next;

解决方法

我认为您在正确的轨道上。该方法工作正常,但似乎您没有对列表进行正确的迭代。这是我测试您的代码的方式:

public class ListNode{
    ListNode next;
    char data;
    public ListNode(char data) {
        this.data = data;
    }
    public ListNode() {}
}
private static ListNode getList(String number){
    int size = number.length();
    int pos = 0;
    ListNode dummyhead = new ListNode();
    ListNode curr = dummyhead;
    while (size > 0){
        curr.next = new ListNode(number.charAt(pos));   
        pos++;
        size--;
        curr = curr.next;
   }
   return dummyhead.next;
}
private static String printList(ListNode head) {
    ListNode n = head;
    StringBuilder sb = new StringBuilder();
    while(n != null) {
        sb.append(n.data+"-");
        n = n.next;
    }
    return sb.toString();
}
public static void main(String[] args) {
    String number = "807";
    System.out.println(printList(getList(number)));
}

输出:

8-0-7-
,

/mnt/dist/python返回指定位置的字符。 charAt是数字类型,但是它表示它所代表字符的ascii地址。

char

返回"807".charAt(0) ,因为那是56的ascii值。

我怀疑您在8中有一个int data字段,该字段将ListNode保存到常规char中。

您的“ 807”将因此转换为数字56、48、55的列表。

您显然想将int保存到节点中,因此请使用

"8"

或者,正如Majed在回答中所建议的那样,将while (size > 0){ //for pos=0,this converts the string "8" to the integer 8: Integer n = Integer.valueOf(number.substring(pos,pos+1)); curr.next = new ListNode(n); 内的data字段的类型更改为ListNode