String to a singly linked list

Viewed 601

I am trying to convert a string to a linked list where each digit is in a separate node.

I set on it trying to debug it but I can't seem to find what's wrong with my logic. I keep getting a weird 2-digit number in each node and not necessarily even the digits that appear in the string.

Please note the ListNode is the class I create a new node object with.

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;
2 Answers

I think you're on the right track. The method works fine, but it seems you are not iterating the list right. Here is how I tested your code:

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

Output:

8-0-7-

charAt returns the character of the specified position. A char is a numeric type, but it represents the ascii address of the character it represents.

"807".charAt(0)

returns 56 because that is the ascii value of 8.

I suspect that you have a int data field inside ListNode, which saves that char into a regular int.

Your "807" will thus be transformed into a list of the numbers 56, 48, 55.

You apparently want to save that "8" into the node, so use

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

Or, as Majed suggests in his answer, change the type of your data field inside of ListNode to char.

Related