Skip to content

Commit 18032f6

Browse files
realDuYuanChaogithub-actions
andauthored
reverse linked list (examplehub#92)
* reverse-linked-list * Formatted with Google Java Formatter Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
1 parent 4eb992a commit 18032f6

2 files changed

Lines changed: 39 additions & 0 deletions

File tree

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package com.examplehub.leetcode.easy;
2+
3+
import com.examplehub.leetcode.ListNode;
4+
5+
/** https://leetcode.com/problems/reverse-linked-list/ */
6+
public class ReverseLinkedList {
7+
public static ListNode solution1(ListNode head) {
8+
ListNode prev = null;
9+
ListNode cur = head;
10+
while (cur != null) {
11+
ListNode nextTemp = cur.next;
12+
cur.next = prev;
13+
prev = cur;
14+
cur = nextTemp;
15+
}
16+
return prev;
17+
}
18+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package com.examplehub.leetcode.easy;
2+
3+
import static org.junit.jupiter.api.Assertions.*;
4+
5+
import com.examplehub.leetcode.ListNode;
6+
import com.examplehub.utils.NodeUtils;
7+
import org.junit.jupiter.api.Test;
8+
9+
class ReverseLinkedListTest {
10+
@Test
11+
void testSolution1() {
12+
ListNode head = NodeUtils.makeList(1, 2, 3, 4, 5);
13+
assertEquals("5->4->3->2->1", ReverseLinkedList.solution1(head).toString());
14+
15+
head = NodeUtils.makeList(1, 2);
16+
assertEquals("2->1", ReverseLinkedList.solution1(head).toString());
17+
18+
head = NodeUtils.makeList();
19+
assertSame(null, ReverseLinkedList.solution1(head));
20+
}
21+
}

0 commit comments

Comments
 (0)