Remove Duplicates from Sorted List II問題と解法

1233 ワード

問題の説明:
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
例:Given 1->2->3->3->4->4->5、return 1->2->5.Given  1->1->1->2->3 , return  2->3 . 問題の分析:
各要素を判断し、前の要素と後の要素が等しくない場合は保持し、そうでない場合は削除します.
プロセスの詳細は、コードを参照してください.
/**
 * 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) {
   
        ListNode *ptr = NULL, *res = NULL, *last = NULL;
		if (head == NULL) return head;
		while (head)
		{
			if (head->next== NULL || head->val != head->next->val)
			{
				if (last == NULL)
				{
					ptr = head;
					res = head;
				}
				else if (head->val != last ->val)
				{
					if (ptr == NULL)
					{
						ptr = head;
						res = head;
					}
					else
					{
						ptr->next = head;
						ptr = ptr->next;
					}
				}
				
			}
        
			last = head;
			head = head->next;
		}
		if(ptr) ptr->next = NULL;
		return res;
    }
};