LintCode-- Remove Linked List Elements

Remove all elements from a linked list of integers that have valueval.

样例

Given 1->2->3->3->4->5->3, val = 3, you should return the list as1->2->4->5

 

 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    /**
     * @param head a ListNode
     * @param val an integer
     * @return a ListNode
     */
    public ListNode removeElements(ListNode head, int val) {
        // Write your code here
        if (head == null) {
            return head;
        }
        
        ListNode cur = head;
        ListNode returnHead = new ListNode(-1);
        returnHead.next = cur;
        ListNode pre = returnHead;
        
        while (cur != null) {
            if (cur.val == val) {
                pre.next = cur.next;
            } else {
                pre = pre.next;
            }
            cur = cur.next;
        }
        
        return returnHead.next;
    }
}

  

posted @ 2015-10-21 21:41  feiling  阅读(218)  评论(0编辑  收藏  举报