This commit is contained in:
whai 2024-01-05 22:41:13 +08:00
parent 8765a0f989
commit 929adbf6bb
2 changed files with 84 additions and 0 deletions

View File

@ -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;
}
}
}
}

View File

@ -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逆转3tmp 2.next为下次递归的输入
ListNode tmp = cur.next;
cur.next = pre;
return reverse(cur, tmp);
}
}
}