Skip to content

Commit e907f88

Browse files
committed
[LeetCode] Reverse Linked List
1 parent 8be34fc commit e907f88

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package linkedlist;
2+
3+
public class LinkedListReverse {
4+
5+
/**
6+
* Reverse a singly linked list.
7+
* <p>
8+
* In this algorithm, each node will be moved exactly once.
9+
* Therefore, the time complexity is O(N),
10+
* where N is the length of the linked list.
11+
* <p>
12+
* We only use constant extra space so the space complexity is O(1).
13+
*/
14+
public ListNode reverseList(ListNode head) {
15+
ListNode reversed = null;
16+
ListNode before = null;
17+
ListNode cursor = head;
18+
ListNode next;
19+
20+
while (cursor != null) {
21+
next = cursor.next;
22+
cursor.next = before;
23+
reversed = cursor;
24+
before = cursor;
25+
cursor = next;
26+
}
27+
28+
return reversed;
29+
}
30+
31+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package linkedlist;
2+
3+
import lombok.val;
4+
import org.junit.Test;
5+
6+
import static org.junit.Assert.assertEquals;
7+
8+
public class LinkedListReverseTest {
9+
10+
@Test
11+
public void reverseListExample1() {
12+
13+
// given: 1->2->3->4->5->NULL
14+
val node1 = new ListNode(1);
15+
val node2 = new ListNode(2);
16+
val node3 = new ListNode(3);
17+
val node4 = new ListNode(4);
18+
val node5 = new ListNode(5);
19+
node1.next = node2;
20+
node2.next = node3;
21+
node3.next = node4;
22+
node4.next = node5;
23+
24+
// when
25+
val reversed = new LinkedListReverse().reverseList(node1);
26+
27+
// then
28+
assertEquals(node5, reversed);
29+
assertEquals(node4, reversed.next);
30+
assertEquals(node3, reversed.next.next);
31+
assertEquals(node2, reversed.next.next.next);
32+
assertEquals(node1, reversed.next.next.next.next);
33+
}
34+
}

0 commit comments

Comments
 (0)