203. Remove Linked List Elements

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode removeElements(ListNode head, int val) {
        if(head==null)
            return null;
        ListNode temp=head;
        ListNode tail=null;
        while(temp!=null)
        {
            if(temp.val==val)
            {
                if(tail==null)
                {
                    head=temp.next;
                }
                else
                {
                    tail.next=temp.next;
                }
            }
            else
            {
                tail=temp;
            }
            temp=temp.next;
        }
        return head;
    }
}

 

posted @ 2016-04-02 21:04  阿怪123  阅读(83)  评论(0编辑  收藏  举报