Liondancer
Liondancer

Reputation: 16469

Creating and chaining LinkedList in for loop

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

Upvotes: 0

Views: 74

Answers (1)

aasu
aasu

Reputation: 472

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

Upvotes: 1

Related Questions