leetcode83.删除排序链表中的重复元素

1.题目:
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
2.示例:
示例 1:
输入: 1->1->2
输出: 1->2
示例 2:
输入: 1->1->2->3->3
输出: 1->2->3
3.思路
遍历链表,跳过重复节点。
4.代码
代码1:存储节点的值比较,释放重复节点内存
ListNode* deleteDuplicates(ListNode* head) {
if(head= =NULL||head->next= =NULL) return head;
ListNode* pre=head;
ListNode* ptr=head->next;
int val=head->val;
while(ptr!=NULL){
if(ptr->val= =val){
ListNode* del=ptr;
pre->next=ptr->next;
ptr=ptr->next;
delete del;
}
else{
val=ptr->val;
pre=ptr;
ptr=ptr->next;
}
}
return head;
}
代码2:直接跳过重复节点,不需要释放内存。
ListNode* deleteDuplicates(ListNode* head) {
if(head= =NULL||head->next= =NULL) return head;
ListNode* ptr=head;
while(ptr->next!=NULL){
if(ptr->val= =ptr->next->val)
ptr->next=ptr->next->next;
else
ptr=ptr->next;
}
return head;
}

猜你喜欢

转载自blog.csdn.net/qq_14962179/article/details/85597730