Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Henry Wang
Henry Wang
6,412 Points

Swapping Nodes of a LinkedList

I am trying to swap the adjacent nodes of a Linked List, but when I test my code using [] as input, I am getting NullPointerException instead of runtime error (which is what the online judge wants).

Could someone please take a look at my code and see what's going wrong?

Thanks!

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode node) {

        if (node.next == null) {
            return node;
        }

        if (node == null) {
            return 
        }


        swap(node);

        return node;
    }

    public static void swap(ListNode node) {
        ListNode temp = new ListNode(node.val);
        temp.next = node.next;

        ListNode tempNext = new ListNode(node.next.val);
        tempNext.next = node.next.next;

        // Begin Swapping
        node.val = node.next.val;
        node.next = temp;

        if (tempNext == null) {
            node.next.next = null;

        } else {
            temp.next = tempNext.next;

        }


        if (node.next.next != null) {
            swap(node.next.next);
        } 




    }


}
Steven Parker
Steven Parker
231,269 Points

Can you provide a link to the page (with the "online judge")?

1 Answer

Steven Parker
Steven Parker
231,269 Points

This doesn't look like it would compile. The "return" on line 17 is missing both the return value and the semicolon to end the statement.

If that's not the whole issue, please make a snapshot of your workspace and post the link to it here. Or post a link to the course page if it's from a challenge.