乌!蒙!山!连!着!山!外!山!
题目:
思路:
双指针,slow和fast,并且增加标记flag初始为1。
如果slow指向节点值等于fast指向节点值,fast向后走,flag置为0;
如果slow指向节点值不等于fast指向节点值,观察flag的值若为0,slow指向fast,fast向后走,flag置为1,然后continue;观察flag的值若不为0,将该节点拿下来,成为我们的目标节点去处理。
剩下的就是细节以及最后一个节点的问题,比较简单,判断一下就好。
代码:
struct ListNode* deleteDuplicates(struct ListNode* head)
{
// write code here
if (head == NULL || head->next == NULL)
return head;
struct ListNode* tail = NULL;
struct ListNode* newhead = NULL;
struct ListNode* slow = head;
struct ListNode* fast = slow->next;
int flag = 1;
while (fast)
{
if (slow->val == fast->val)
{
fast = fast->next;
flag = 0;
}
else
{
if (flag == 0)
{
slow = fast;
fast = fast->next;
flag = 1;
continue;
}
if (newhead == NULL)
{
tail = newhead = slow;
}
else
{
tail->next = slow;
tail = slow;
}
slow = fast;
fast = fast->next;
}
}
if (flag == 1)
{
if (tail)
tail->next = slow;
else
newhead = slow;
}
else
{
if (tail)
tail->next = NULL;
}
return newhead;
}
个人主页:Lei宝啊
愿所有美好如期而遇