玉颜不及寒鸦色
犹带昭阳日影来
C++,链表题。
对,链表题往往都不难,就是麻烦。。。
其实就是找到连续重复子序列的左右端点,然后删就行了。当然OJ没法判断你删没删,实际上你只要移动指针改变指向就好了哈哈哈。
有个屡试不爽的技巧,就是在原链表前加个头。
详细见代码:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* deleteDuplication(ListNode* pHead) {
if (!pHead) return nullptr;
ListNode *dummy = new ListNode(0);
dummy->next = pHead;
ListNode *slow = dummy;
ListNode *quick = pHead;
while (quick && quick->next) {
if (quick->val == quick->next->val) {
ListNode *p = quick->next;
while (p && quick->val == p->val) p = p->next;
delete_node(quick, p);
quick = p;
slow->next = quick;
} else {
slow = slow->next;
quick = quick->next;
}
}
return dummy->next;;
}
void delete_node(ListNode *left, ListNode *right) {
ListNode *p = left;
while (p != right) {
ListNode *q = p->next;
free(p);
p = q;
}
}
};