【LeetCode】82. Remove Duplicates from Sorted List II(C++)

地址:https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/

题目:

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

Example 1:

Input: 1->2->3->3->4->4->5
Output: 1->2->5

Example 2:

Input: 1->1->1->2->3
Output: 2->3

理解:

一个有序链表中,删除重复值,只留下那些单独的元素。

实现:

pre:目前已经处理的部分的尾指针
p:工作指针,指向要开始处理部分的第一个位置
q:工作指针,最后会指向不等于p的第一个位置

class Solution {
public:
	ListNode* deleteDuplicates(ListNode* head) {
		ListNode* pre = nullptr;
		ListNode* p = head;
		while (p) {
			ListNode* q = p->next;
			while (q && q->val == p->val)
				q = q->next;
			// if no duplicates, add p to down area
			if (q == p->next) {
				pre = p;
			}
			else {
				// has down area, add to the back
				if (pre) {
					pre->next = q;
				}
				// don't have down area, need to modify the head pointer
				else {
					head = q;
				}
			}
			p = q;
		}
		return head;
	}
};

猜你喜欢

转载自blog.csdn.net/Ethan95/article/details/84923218