0

I am trying to create a new LinkedListNode object as I parse through a char[] in reverse. Then I want to link these

    char[] totalnum = (total + "").toCharArray();
    for (int i = totalnum.length; i > 0; i--) {
        LinkedListNode sum = new LinkedListNode(totalnum[i]);
        sum.next = null;
    }

Here is my LinkedListNode class:

public class LinkedListNode {
    int data;
    public LinkedListNode next;

    // constructor
    public LinkedListNode(int newData) {
        this.next = null;
        this.data = newData;
    }
}

I was wondering how can I go about doing this. I am new to Java so this has gotten me stumped! I know I should create a new LinkedListNode object in each iteration but that is as far as I have gotten

1
  • sorry I htought i finished! Commented Feb 6, 2014 at 7:47

1 Answer 1

1
public class LinkedListNode {
    int data;
    private LinkedListNode next;

    public LinkedListNode(int data) {
        this.data = data;
    }

    public void setNext(LinkedListNode next) {
        this.next = next;
    }

    public LinkedListNode getNext() {
        return next;
    }
}

char[] totalNum = (total + "").toCharArray();
int length = totalNum.length;

LinkedListNode tail /*or 'head', whatever suits you*/ = new LinkedListNode(totalNum[length - 1]);
LinkedListNode newNode;
LinkedListNode previousNode = tail;

for (int i = length - 2; i >= 0; i--) {
    newNode = new LinkedListNode(totalNum[i]);
    previousNode.setNext(newNode);
    previousNode = newNode;
}
Sign up to request clarification or add additional context in comments.

2 Comments

My char array is 7550. However when I tried your code I am getting the output 48,48,53,53 as my linked list when i return tail
well, it should be 48, 53, 53, 55 which are ASCII codes for 0, 5, 5, 7 respectively. How are you finally printing your linked list? Also, I'm sorry, the length variable should be totalNum.length (without parentheses basically) updated answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.