leetcode 203. Remove Linked List Elements

版权声明:大家说好才是真的吼,承蒙看官老爷厚爱。欢迎常来茶馆做客 https://blog.csdn.net/icurious/article/details/78325619

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

/**
 * 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* dummyNode=new ListNode(0);
        dummyNode->next=head;
        ListNode* cur=dummyNode;
        while(cur->next!=NULL){
            if (cur->next->val==val){
                ListNode* delNode=cur->next;
                cur->next=delNode->next;
                delete delNode;
            }
            else {
                cur=cur->next;
            }
        }
        ListNode* retNode=dummyNode->next;
        return retNode;
    }
};


展开阅读全文

没有更多推荐了,返回首页