LeetCode 203. Remove Linked List Elements
原题链接:https://leetcode.com/problems/remove-linked-list-elements/
题目:
Remove all elements from a linked list of integers that have value val.
Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5
题解:
建一个dunmy,dunmy.next = head,为了防止head.val 等于要被去掉的value时删掉head不方便表示。
Time Complexity: O(n), n是list长度. Space: O(1).
AC Java:
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public ListNode removeElements(ListNode head, int val) { 11 if(head == null){ 12 return head; 13 } 14 15 ListNode dummy = new ListNode(0); 16 dummy.next = head; 17 ListNode cur = dummy; 18 while(cur.next != null){ 19 if(cur.next.val == val){ 20 cur.next = cur.next.next; 21 }else{ 22 cur = cur.next; 23 } 24 } 25 return dummy.next; 26 } 27 }
Recursion Method, stop condition 是 head == null, return head.
Time Complexity: O(n), n 是list长度. Space: O(n), stack space.
AC Java:
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public ListNode removeElements(ListNode head, int val) { 11 if(head == null){ 12 return head; 13 } 14 head.next = removeElements(head.next, val); 15 return head.val == val ? head.next : head; 16 } 17 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】博客园2025新款「AI繁忙」系列T恤上架,前往周边小店选购
【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合会员
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步