LC.203. Remove Linked List Elements

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.

Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 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     }

 

posted @ 2018-02-23 08:27  davidnyc  阅读(93)  评论(0编辑  收藏  举报