83. Remove Duplicates from Sorted List
Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Input: 1->1->2
Output: 1->2
Example 2:
Input: 1->1->2->3->3
Output: 1->2->3
解题思路:
遍历链表,当前结点与前驱结点值相同时,将前驱结点的next指向当前结点的next
1.双指针法:
/*
执行用时 : 8 ms, 在Remove Duplicates from Sorted List的C提交中击败了98.78% 的用户
内存消耗 : 7.8 MB, 在Remove Duplicates from Sorted List的C提交中击败了5.21% 的用户
*/
/*
添加了特殊情况的head->next == NULL,执行时间从8ms到4ms
执行用时 : 4 ms, 在Remove Duplicates from Sorted List的C提交中击败了99.88% 的用户
内存消耗 : 7.8 MB, 在Remove Duplicates from Sorted List的C提交中击败了5.21% 的用户
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* deleteDuplicates(struct ListNode* head){
if(head == NULL || head->next == NULL){
return head;
}
struct ListNode* p = head->next;
struct ListNode* q = head;
while(p!=NULL){
if(p->val == q->val){
q->next = p->next;
free(p);
p = q->next;
}
else{
p = p->next;
q = q->next;
}
}
return head;
}
2.单指针法:
struct ListNode* deleteDuplicates(struct ListNode* head){
if(head == NULL || head->next == NULL){
return head;
}
struct ListNode* p = head;
while(p!=NULL && p->next != NULL){
if(p->next->val == p->val){
p->next = p->next->next;
}
else{
p = p->next;
}
}
return head;
}
后记:
对特殊情况的考虑可以减少执行时间
LeetCode 82. Remove Duplicates from Sorted List II(删除排序链表中的重复元素 II)--c语言