JavaWannabee
JavaWannabee

Reputation: 91

Switch values in a linked list (dealing with nodes)

I'm writing a method to switch a pair of value in a linked list.

For example, my list contains:

1, 4, 5, 8, 9, 3

after the method call, the list should contains:

4, 1, 8, 5, 3, 9

dealing with linked list is confusing me by using nodes only, and i don't understand why my code only switch the first 2 values in the list. Any ideas? A little more explanation would be great. Thank you.

public void switchPairs() {
    ListNode current = front;
    ListNode temp = front.next;
    while(current.next != null) {
        int i = front.data;
        front.data = front.next.data;
        front.next.data = i;

        current = current.next;
    }
}

Upvotes: 0

Views: 1658

Answers (2)

user3256147
user3256147

Reputation: 398

This is because you are not altering the front value. All the time the front alters between the first and the second number . But as the current is set to front initially, each time current value gets incremented till it reaches thd last value

Upvotes: 1

Change your ListNode variable names to first and second, and it will be easier to spot the issues. You don't properly swap nor do you properly iterate both ListNodes. You must iterate both by 2.

public void switchPairs() {
    ListNode first = front;//first node in pair
    ListNode second = front.next;//second node in pair

    //while the both nodes are not null
    while(first != null && second != null) {
        int i = first.data;//put first value in temp value
        first.data = second.data;//put second value in first node
        second.data = i;//put temp value (first value) in second node

        //NOTE:  do some null pointer checks here just in case
        first = second.next;//iterate first node
        second = second.next.next;//iterate second node
    }
}

Upvotes: 2

Related Questions