Leetcode 203 Remove Linked List Elements

2018-01-12 14:47:11 浏览数 (1)

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

删除链表里的指定元素。

简单题,不做复杂解释了

代码语言:javascript复制
/**
 * 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 = new ListNode(-1);
        p->next = head;
        ListNode* q = p;
        while(p->next)
        {
            if(p->next->val == val) 
                p->next = p->next->next;
            else
                p = p->next;
        }
        return q->next;
    }
};

0 人点赞