原题地址:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii/description/
题目描述:
给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。
示例 1:
输入: 1->2->3->3->4->4->5
输出: 1->2->5
示例 2:
输入: 1->1->1->2->3
输出: 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) {
if(!head || !head->next)
return head;
ListNode* p = head->next;
ListNode* q;
int tmp = head->val;
int flag = 0;
while(p && tmp == p->val){
while(p && tmp == p->val)
p = p->next;
head = p;
if(!head || !head->next) return head;
p = head->next;
tmp = head->val;
}
q = head;
p = q->next;
tmp = p->val;
while(p->next){
if(p->next->val == tmp){
flag = 1;
}
else if(flag == 0){
q->next = p;
q = q->next;
tmp = p->next->val;
}
else{
flag = 0;
tmp = p->next->val;
}
p = p->next;
}
if(flag == 0)
q->next = p;
else
q->next = NULL;
return head;
}
};