My Slightly complex solution C++ (12ms) with two pointers


  • 0
    2

    //find head node

    void findHead(ListNode*& head,ListNode*& p,ListNode*& q)
    {

    if (!head || !q || p->val != q->val)
    {
    	return;
    }
    bool flag = false;
    while (q && p->val == q->val)
    {
    	flag = true;
    	q = q->next;
    	p = p->next;
    }
    if (flag)
    {
    	head = q;
    	if (q)
    	{
    		q = q->next;
    	}
    	if (p)
    	{
    		p = p->next;
    	}
    	flag = false;
    }
    findHead(head,p,q);
    

    }

    ListNode* deleteDuplicates(ListNode* head) {
    if (!head || !head->next)
    {
    	return head;
    }
    ListNode* p = head;
    ListNode* q = head->next;
    findHead(head,p,q);
    bool flag = false;
    while (q)
    {
    	//meet duplicate node
    	if (q->next && q->val == q->next->val)
    	{
    		flag = true;
    		q = q->next;
    		continue;
    	}
    	if (flag)
    	{
    		p->next = q->next;
    		q = q->next;
    		flag = false;
    	}
    	else
    	{
    		p = p->next;
    		q = q->next;
    	}
    }
    return head;
    }

Log in to reply
 

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