【问题标题】:String to a singly linked list字符串到单链表
【发布时间】:2020-12-03 18:27:35
【问题描述】:

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

我开始尝试调试它,但我似乎找不到我的逻辑有什么问题。 我在每个节点中不断得到一个奇怪的 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;

【问题讨论】:

    标签: java string pointers linked-list


    【解决方案1】:

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

    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-
    

    【讨论】:

      【解决方案2】:

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

      "807".charAt(0)
      

      返回 56,因为那是 8 的 ascii 值。

      我怀疑您在ListNode 中有一个int data 字段,这会将char 保存为常规int

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

      您显然想将 "8" 保存到节点中,所以使用

      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);
      

      或者,正如 Majed 在他的回答中所建议的,将 ListNode 内的 data 字段的类型更改为 char

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-11
        • 1970-01-01
        相关资源
        最近更新 更多