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

注意是不是头结点就ok了。

C++实现代码:

/**

 * Definition for singly-linked list.

 * struct ListNode {

 *     int val;

 *     ListNode *next;

 *     ListNode(int x) : val(x), next(NULL) {}

 * };

 */

class Solution {

public:

    ListNode* removeElements(ListNode* head, int val) {

        if(head==NULL)

            return NULL;

        ListNode *p=head;

        ListNode *pre=head;

        while(p)

        {

            if(p->val==val)

            {

                if(p==head)

                {

                    head=p->next;

                    p->next=NULL;

                    delete p;

                    pre=head;

                    p=head;

                }

                else

                {

                    pre->next=p->next;

                    p->next=NULL;

                    delete p;

                    p=pre->next;

                }

            }

            else

            {

                pre=p;

                p=p->next;

            }

        }

        return head;

    }

};

 

你可能感兴趣的:(element)