My C++ code 40ms


  • 0
    G
    /**
    * 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 == nullptr)return head;
    		ListNode* my_head = (ListNode*)malloc(sizeof(ListNode));
    		my_head->next = head;
    		ListNode* pre_head = my_head;
    		while (head)
    		{
    			if (head->val == val)
    			{
    				pre_head->next = head->next;
    				free(head);
    				head = pre_head->next;
    			}
    			else
    			{
    				pre_head = head;
    				head = head->next;
    			}
    		}
    		head = my_head->next;
    		free(my_head);
    		return head;
    	}
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.