一、题目描述
删除所有重复的节点,输出删除后的链表
Example 1:
Input: 1->2->3->3->4->4->5 Output: 1->2->5
二、思路
1.新建一个节点,使它指向头节点,before_head->next = head
2.设两个指针p1、p2,开始p1指向新建的节点,p2指向头节点,p1 = before_head,p2 = head
3.循环,p2去寻找重复的节点,并删除,p1记录初始的位置,方便记录
4.返回before_head->next
三、C代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* deleteDuplicates(struct ListNode* head)
{
struct ListNode* before_head = (struct ListNode *)malloc(sizeof(struct ListNode));
before_head->next = head;
struct ListNode* p1 = before_head;
struct ListNode* p2 = head;
while(p2!=NULL)
{
int should_del = 0;
while(p2->next!=NULL && p2->val == p2->next->val)
{
should_del = 1;
p2 = p2->next;
}
if(should_del)
p1->next = p2->next;
else
p1 = p1->next;
p2 = p1->next;
}
return before_head->next;
}