LeetCode(203): Remove Linked List Elements

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

题意:给定一个链表,删除给定的元素。

思路:对应本题可以使用双指针进行求解。求解的过程中要注意判断一些特殊的情况:链表为空和链表的前n个元素都为给定的元素等。

代码:

public ListNode removeElements(ListNode head, int val) {
        if(head==null) return null;
        while(head.val==val){
            if(head.next!=null)
            {
             head = head.next;
            }else{
                return null;
            }
        }
        if(head == null) return null;
        ListNode p=head,q=null;
        while(p!=null){
            if(p.val!=val){
                q = p;
            }else{
                q.next=p.next;
            }
            p=p.next;
        }
        return head;
    }
posted @ 2016-01-14 19:16  Lewisr  阅读(102)  评论(0编辑  收藏  举报