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![](https://ecs-static.teamtreehouse.com/assets/views/marketing/shared/community-banner-white-47072046c51352fe6a69f5e691ff5700b28bb11d45197d7bdf066d9ea3f72d0c.webp)
![Henry Wang](https://uploads.teamtreehouse.com/production/profile-photos/9819652/micro_Razer-Backgrounds.jpg)
Henry Wang
6,412 PointsSwapping 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);
}
}
}
1 Answer
![Steven Parker](https://uploads.teamtreehouse.com/production/profile-photos/969492/micro_tool_chess_set_2.jpg)
Steven Parker
230,688 PointsThis 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.
Steven Parker
230,688 PointsSteven Parker
230,688 PointsCan you provide a link to the page (with the "online judge")?