Leetcode之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

代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* delDuplicate(ListNode* p) {
	while (p) {
		if (!p->next || p->val == p->next->val) {
			p = p->next;
		}
		else { p = p->next; break; }
	}
	return p;
}
    ListNode* deleteDuplicates(ListNode* head) {
        if (!head)return head;
	ListNode* first = new ListNode(0);
	ListNode* p = first;

	while (head) {
		while (head->next&&head->val == head->next->val) {
			head = delDuplicate(head);
			if (!head)break;
		}
		p->next = head;
		if (!head)continue;
		p = p->next;
		head = head->next;
		
	}
	return first->next;
    }
};

想法:

考虑head为NULL的情况

猜你喜欢

转载自blog.csdn.net/qq_35455503/article/details/89468744