Skip to content

Commit cfe73ee

Browse files
authored
Merge pull request #91 from jaebradley/reverse-linked-list
linked list reverser
2 parents eff7aef + 49bfb55 commit cfe73ee

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package problems.impl;
2+
3+
public class LinkedListReverser {
4+
public static class ListNode {
5+
int val;
6+
ListNode next;
7+
ListNode(int x) { val = x; }
8+
}
9+
10+
public static ListNode reverse(ListNode head) {
11+
if (head == null) {
12+
return null;
13+
}
14+
15+
ListNode current = head;
16+
ListNode previous = null;
17+
ListNode next;
18+
19+
while (current.next != null) {
20+
next = current.next;
21+
current.next = previous;
22+
previous = current;
23+
current = next;
24+
}
25+
26+
current.next = previous;
27+
return current;
28+
}
29+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package problems.impl;
2+
3+
import org.junit.Test;
4+
import problems.impl.LinkedListReverser.ListNode;
5+
6+
import static org.junit.Assert.*;
7+
8+
public class LinkedListReverserTest {
9+
10+
@Test
11+
public void nullForEmptyLinkedList() {
12+
assertNull(LinkedListReverser.reverse(null));
13+
}
14+
15+
@Test
16+
public void headForSingleValueList() {
17+
ListNode head = new ListNode(0);
18+
19+
assertEquals(head, LinkedListReverser.reverse(head));
20+
}
21+
22+
@Test
23+
public void reverseValues() {
24+
ListNode head = new ListNode(0);
25+
ListNode one = new ListNode(1);
26+
ListNode two = new ListNode(2);
27+
ListNode three = new ListNode(3);
28+
head.next = one;
29+
one.next = two;
30+
two.next = three;
31+
32+
ListNode reversed = LinkedListReverser.reverse(head);
33+
34+
assertEquals(3, reversed.val);
35+
assertEquals(2, reversed.next.val);
36+
assertEquals(1, reversed.next.next.val);
37+
assertEquals(0, reversed.next.next.next.val);
38+
assertNull(reversed.next.next.next.next);
39+
}
40+
}

0 commit comments

Comments
 (0)