Remove Linked List Elements——LeetCode

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

题目大意:给定一个链表,删除所有等于指定的值的元素。

解题思路:这种题目肯定要一次遍历才能过,记录前驱节点,当下一个节点等于指定的值的时候,继续循环找到不等的x节点,然后将前驱的next节点赋为x。

Talk is cheap>>

    public ListNode removeElements(ListNode head, int val) {

        if(head==null){

            return null;

        }

        while(head!=null&&head.val==val){

            head=head.next;

        }

        ListNode ptr = head;

        while(ptr!=null){

            ListNode pre = ptr;

            ptr=ptr.next;

            while(ptr!=null&&ptr.val==val){

                ptr=ptr.next;

            }

            pre.next = ptr;

        }

        return head;

    }

 

你可能感兴趣的:(LeetCode)