Remove duplicates from sorted list


  • 0
    S
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
       ListNode* deleteDuplicates(ListNode* head) {
    		if (head == NULL || head->next == NULL)
    			return head;
    		ListNode * newHead = new ListNode(INT_MIN);
    		newHead->next = head;
    		//print(newHead->next);
    		auto pre = newHead, ptr = newHead->next;
    
    		while (ptr != NULL){
    			if (ptr->next == NULL)
    				return newHead->next;
    			if (ptr->val == ptr->next->val){
    				auto p = ptr->next;
    				while (p != NULL && p->val == ptr->val)
    					p = p->next;
    				pre->next = p;
    			}
    			else
    				pre = pre->next;
    			ptr = pre->next;
    		}
    		return newHead->next;
    	}
    };

Log in to reply
 

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