LeetCode: Remove Duplicates from Sorted List II

思路:这个题目又是缝缝补补过的,利用指针q指示当前待审查元素,p为指向剩下链表(删除重复元素后)的最后一个元素,t为新元素,找到t->val != q ->val 然后将p 指向 t,删除了中间重复的元素,如果t 就是q 指向的元素,那么不用删除,p,q的位置都要移动。

class Solution {
public:
    ListNode *deleteDuplicates(ListNode *head) {
		if(head){
			ListNode *p, *q, *t;
			p = q = head;
			t = head->next;
			bool flag = 0;
			while(t){
				if(t->val != q->val){	
					if(head->next != t  && q == head){p = q = head = t;}
					else{
						if(t == q->next) p = q;
						p->next = t;
						q = t;
					}
					flag = 0;
				}
				else
					flag = 1;
				t = t->next;
			}
			if(q->next)p->next = t;
			if(q==head && flag == 1) head = NULL;
		}
		return head;
    }
};


你可能感兴趣的:(LeetCode: Remove Duplicates from Sorted List II)