--
This commit is contained in:
parent
8765a0f989
commit
929adbf6bb
52
src/main/java/cn/whaifree/redo/LeetCode203.java
Normal file
52
src/main/java/cn/whaifree/redo/LeetCode203.java
Normal 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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
32
src/main/java/cn/whaifree/redo/LeetCode206.java
Normal file
32
src/main/java/cn/whaifree/redo/LeetCode206.java
Normal 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逆转,3(tmp 2.next)为下次递归的输入
|
||||
ListNode tmp = cur.next;
|
||||
cur.next = pre;
|
||||
return reverse(cur, tmp);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user