LeetCode 83. 删除排序链表中的重复元素 | C语言版
LeetCode 83. 删除排序链表中的重复元素
题目描述
题目地址:83. 删除排序链表中的重复元素
给定一个已排序的链表的头 head , 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。
解题思路
思路一:使用双指针
代码实现
/**
* 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;
}
//cur初始化为头节点
struct ListNode* cur=head;
//next初始化为NULL
struct ListNode* next=NULL;
while(cur!=NULL){
//next为头节点的下一个节点
next=cur->next;
while(next!=NULL){
if(cur->val==next->val){
//如果两指针(相邻)指向的节点相等,则将cur的指针域指向next的的下一个节点
cur->next=next->next;
}
next=next->next;
}
cur=cur->next;
}
return head;
}
运行结果
参考文章:
思路二:减少遍历节点数
代码实现
在这里插入代码片
运行结果
参考文章:
LeetCode 82. 删除排序链表中的重复元素 II
题目描述
题目地址:82. 删除排序链表中的重复元素 II
给定一个已排序的链表的头 head , 删除原始链表中所有重复数字的节点,只留下不同的数字 。返回 已排序的链表 。
解题思路
思路一:使用三指针
代码实现
/**
* 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;
}
//设置虚拟节点,指向head(减少边界判断)
struct ListNode* dummyHead=(struct ListNode*)malloc(sizeof(struct ListNode));
dummyHead->next=head;
//last保存重复节点段的最后一个节点
struct ListNode* last=dummyHead;
//pre保存当前节点cur的前驱节点
struct ListNode* pre=dummyHead;
//当前节点cur
struct ListNode* cur=pre->next;
//dummyHead(pre)->head(cur)->...
while(cur!=NULL){
if(pre->val!=cur->val && (cur->next==NULL || cur->val!=cur->next->val)){
last->next=cur;
last=last->next;
}
//pre=pre->next;
pre=cur;
cur=cur->next;
}
last->next=NULL;
return dummyHead->next;
}
运行结果
参考文章:
思路二:减少遍历节点数
代码实现
在这里插入代码片