lintcode-easy-Remove Linked List Elements

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

 Example

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

 

看起来这题不难,但是还是有些地方需要注意,据说面试要做到bug-free

 

p = p.next;执行之后,p有可能是null,所以在循环条件中要检查p是否为null。

其实任何时候访问一个对象的成员之前,都要注意检查这个对象是否为null,否则会出现异常。

/**
 * 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 fakehead = new ListNode(0);
        fakehead.next = head;
        
        ListNode p = fakehead;
        
        while(p!= null && p.next != null){
            while(p.next != null && p.next.val == val){
                p.next = p.next.next;
            }
            
            p = p.next;
        }
        
        return fakehead.next;
    }
}

 

 

posted @ 2016-02-18 13:06  哥布林工程师  阅读(137)  评论(0编辑  收藏  举报