[LeetCode]203. 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

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

 

Subscribe to see which companies asked this question.

 

指定2个指针,cur  pre;

当cur!=null ,repeat:

  当cur.val==val 时,pre.next  指向 cur.next;

  当cur.val != val 时,pre = pre.next;(pre 向后移动)

  cur 向后移动

 

 1 public class Solution {
 2     public ListNode removeElements(ListNode head, int val) {
 3    ListNode head_pre = new ListNode(-1);
 4         head_pre.next = head;
 5         ListNode  pre = head_pre;
 6         ListNode  cur = head;
 7         while(cur != null){
 8             if(cur.val == val)
 9                 pre.next = cur.next;
10             else
11                 pre = pre.next;
12             cur = cur.next;
13         }
14         return head_pre.next;
15 
16     }
17 
18 }

 

posted @ 2017-05-05 00:20  乐乐章  阅读(178)  评论(0编辑  收藏  举报