package LeetCode; public class LeetCode203 { // https://leetcode.com/problems/remove-linked-list-elements/description/ // ä¸ä½¿ç¨èæå¤´ç»ç¹ // æ¶é´å¤æåº¦: O(n) // 空é´å¤æåº¦: O(1) public ListNode removeElements(ListNode head, int val) { // éè¦å¯¹å¤´ç»ç¹è¿è¡ç¹æ®å¤ç while(head != null && head.val == val){ ListNode node = head; head = head.next; } if(head == null) return head; ListNode cur = head; while(cur.next != null){ if(cur.next.val == val){ ListNode delNode = cur.next; cur.next = delNode.next; } else cur = cur.next; } return head; } // å¼äºä¸ä¸ªèæèç¹(ä¸ç¨å¯¹å¤´ç»ç¹ååå¤çäº) public ListNode removeElements2(ListNode head, int val) { // å建èæå¤´ç»ç¹ ListNode dummyHead = new ListNode(0); dummyHead.next = head; ListNode cur = dummyHead; while(cur.next != null){ if(cur.next.val == val ){ ListNode delNode = cur.next; cur.next = delNode.next; } else cur = cur.next; } return dummyHead.next; } // éå½çæ¹å¼æ¥å public ListNode removeElements3(ListNode head, int val) { if(head == null) return head; // ç¨ä¸ä¸ä¸ªèç¹è·valueæ¯è¾ ListNode res = removeElements3(head.next, val); if(head.val == val) return res; else{ head.next = res; return head; } } // éå½çæ¹å¼æ¥å--->å ¶å®å°±æ¯ä¸ä¸ªå串å é¤çé®é¢ã public ListNode removeElements4(ListNode head, int val) { if(head == null) return head; // å é¤éå¤çèç¹ï¼æ¿å°å串 head.next = removeElements4(head.next, val); // 妿头èç¹æ¯è¦å é¤çèç¹ï¼è¿åå串ã妿䏿¯ï¼è¿åå½åå串 return head.val == val ? head.next : head; } public static void main(String[] args) { int[] nums = {1, 2, 6, 3, 4, 5, 6}; ListNode head = new ListNode(nums); System.out.println(head); ListNode res = (new LeetCode203()).removeElements3(head, 6); System.out.println(res); } }