leetcode 203. 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

思路:声明两指针,类似快慢指针,快指针遇到val时跳过,直到值不是val这时修改慢指针的next为快指针,慢指针移到快指针这个位置。

/**
 * 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) {
        ListNode* p = head;
        ListNode* q = head;
        while (p && q) {
            if(p->val == val) {
                if (p == head) {
                    head = p->next;
                    q = head;
                } else {
                    while (p && p->val == val) p = p->next;
                    q->next = p;
                }
            }
            q = p;
            if (p) p = p->next;
        }
        return head;
    }
};
posted on 2018-02-28 16:00  Beserious  阅读(81)  评论(0编辑  收藏  举报