From 929adbf6bbbd6f70fe94b04aeb17efb83579142e Mon Sep 17 00:00:00 2001 From: whai Date: Fri, 5 Jan 2024 22:41:13 +0800 Subject: [PATCH] -- --- .../java/cn/whaifree/redo/LeetCode203.java | 52 +++++++++++++++++++ .../java/cn/whaifree/redo/LeetCode206.java | 32 ++++++++++++ 2 files changed, 84 insertions(+) create mode 100644 src/main/java/cn/whaifree/redo/LeetCode203.java create mode 100644 src/main/java/cn/whaifree/redo/LeetCode206.java diff --git a/src/main/java/cn/whaifree/redo/LeetCode203.java b/src/main/java/cn/whaifree/redo/LeetCode203.java new file mode 100644 index 0000000..df615f7 --- /dev/null +++ b/src/main/java/cn/whaifree/redo/LeetCode203.java @@ -0,0 +1,52 @@ +package cn.whaifree.redo; + + +import cn.whaifree.leetCode.model.ListNode; +import org.junit.Test; + +public class LeetCode203 { + + @Test + public void test(){ + new Solution().removeElements(ListNode.listNodeFromArray(new int[]{1, 2}), 2).printList(); + } + + + // 使用递归 + /** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ + class Solution { + + public ListNode removeElements(ListNode head, int val) { + return delete(head, val); + } + + // 0 1 2 + public ListNode delete(ListNode head, int val) { + if (head == null) { + return head; + } + + head.next = delete(head.next, val); + if (head.val == val) { + return head.next; + } else { + return head; + } + } + + + + + + } + +} diff --git a/src/main/java/cn/whaifree/redo/LeetCode206.java b/src/main/java/cn/whaifree/redo/LeetCode206.java new file mode 100644 index 0000000..a3ca80c --- /dev/null +++ b/src/main/java/cn/whaifree/redo/LeetCode206.java @@ -0,0 +1,32 @@ +package cn.whaifree.redo; + +import cn.whaifree.leetCode.model.ListNode; +import org.junit.Test; + +// 递归逆转链表 +public class LeetCode206 { + + @Test + public void test() { + ListNode listNode = ListNode.listNodeFromArray(new int[]{1,2,3,4,5}); + ListNode listNode1 = new Solution().reverseList(listNode); + ListNode.printList(listNode1); + } + + class Solution { + public ListNode reverseList(ListNode head) { + return reverse(null, head); + } + + public ListNode reverse(ListNode pre, ListNode cur) { + if (cur == null) { + return pre; + } + // 只考虑三个点,1 2逆转,3(tmp 2.next)为下次递归的输入 + ListNode tmp = cur.next; + cur.next = pre; + return reverse(cur, tmp); + } + + } +}