203. Remove Linked List Elements->Letcode

版权声明:我是一只快乐的小妖精,网络收集与整理和心得,随意取走。 https://blog.csdn.net/qwq1503/article/details/88122809

Problem:

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


//url: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) {
        ListNode* p = head;
        // 当头为空指针时
        if (p == NULL) return NULL;
        
        // 当头只有一个结点,并且为要删除的值时
        if (p->val == val && p->next == NULL){
            //free (p);
            return NULL;
        }
        
        for (ListNode* q = p->next; q != NULL; q = q->next){     
            if (q->val == val){
                p->next = q->next;
                //free(q);
                q = p;  
            }else{
                p = p->next;
            }
        }
        if (head->val == val){
            head = head->next;
        }
        return head;  
    }
};

猜你喜欢

转载自blog.csdn.net/qwq1503/article/details/88122809
今日推荐