Skip to content

Commit 97c39c6

Browse files
realDuYuanChaogithub-actions
andauthored
reverse output linked list (examplehub#130)
* delete target element of singly linkedlist * reverse output linked-list * Formatted with Google Java Formatter Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
1 parent a075174 commit 97c39c6

2 files changed

Lines changed: 55 additions & 0 deletions

File tree

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.examplehub.datastructures.linkedlist;
2+
3+
import com.examplehub.leetcode.ListNode;
4+
import java.util.Stack;
5+
import java.util.StringJoiner;
6+
7+
public class ReverseOutputLinkedList<E> {
8+
private static StringJoiner output1 = new StringJoiner("->");
9+
private static StringJoiner output2 = new StringJoiner("->");
10+
11+
public static String solution1(ListNode head) {
12+
Stack stack = new Stack();
13+
while (head != null) {
14+
stack.add(head.val);
15+
head = head.next;
16+
}
17+
while (!stack.isEmpty()) {
18+
output1.add(stack.pop().toString());
19+
}
20+
return output1.toString();
21+
}
22+
23+
public static String solution2(ListNode head) {
24+
reverseOutputReverse(head);
25+
return output2.toString();
26+
}
27+
28+
public static void reverseOutputReverse(ListNode head) {
29+
if (head != null) {
30+
reverseOutputReverse(head.next);
31+
output2.add(head.val + "");
32+
}
33+
}
34+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package com.examplehub.datastructures.linkedlist;
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 ReverseOutputLinkedListTest {
10+
@Test
11+
void testSolution1() {
12+
ListNode head = NodeUtils.makeList(1, 2, 3, 4, 5);
13+
assertEquals("5->4->3->2->1", ReverseOutputLinkedList.solution1(head));
14+
}
15+
16+
@Test
17+
void testSolution2() {
18+
ListNode head = NodeUtils.makeList(1, 2, 3, 4, 5);
19+
assertEquals("5->4->3->2->1", ReverseOutputLinkedList.solution2(head));
20+
}
21+
}

0 commit comments

Comments
 (0)