前言
给定一个已排序的链表的头 head , 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。
一、代码实现
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
//方法1:
struct ListNode* deleteDuplicates(struct ListNode* head){
if (head == NULL) return head;
struct ListNode *pre_node = head, *iter = head->next;
while (iter)
{
if (iter->val == pre_node->val)
{
while (iter && iter->val == pre_node->val)
{
iter = iter->next;
}
}
pre_node->next = iter;
pre_node = pre_node->next;
if (iter == NULL) break;
iter = iter->next;
}
return head;
}
//方法2:
struct ListNode* deleteDuplicates(struct ListNode* head){
if (head == NULL) return head;
struct ListNode *curr = head;
while (curr->next)
{
if (curr->val == curr->next->val)
{
curr->next = curr->next->next;
}
else
{
curr = curr->next;
}
}
return head;
}