Leetcode 203. Remove Linked List Elements删除链表中特定值val

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

Example:

Input:  1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5

题目链接:https://leetcode.com/problems/remove-linked-list-elements/

/**
 * 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)
            return head;
        ListNode *thead=head;
        while(head&&head->next)
        {
            if(head->next->val==val)
            {
                head->next=head->next->next;
            }
            else
            {
                head=head->next;
            }
        }
        if(thead&&thead->val==val)//如果head->val==val,剔除
            thead=thead->next;
        return thead;
    }
};

猜你喜欢

转载自blog.csdn.net/salmonwilliam/article/details/88574197