230,82,83 是一类题
https://leetcode.com/problems/remove-linked-list-elements/description/Remove all elements from a linked list of integers that have value val. ExampleGiven: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6Return: 1 --> 2 --> 3 --> 4 --> 5
time o(1) space o(1)
1 public ListNode removeElements(ListNode head, int val) { 2 //这里不要写 HEAD.NEXT == NULL 返回 HEAD, 因为会出现 [1], VAL=1 -> [] 3 if (head == null ) return head; 4 ListNode dummy = new ListNode(0) ; 5 ListNode curr = dummy ; 6 dummy.next = head ; 7 /* 8 Given: 1 --> 2 --> 6 --> 6 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6 9 Return: 1 --> 2 --> 3 --> 4 --> 5 10 * */ 11 while (curr != null && curr.next!= null){ 12 if (curr.next.val == val){ 13 curr.next = curr.next.next ; 14 } else{ 15 curr = curr.next ; 16 } 17 } 18 return dummy.next ; 19 }
原文地址:https://www.cnblogs.com/davidnyc/p/8460734.html
时间: 2024-10-08 19:26:05