题目
leetcode
Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
示例
函数
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* deleteDuplicates(struct ListNode* head){
}
分析
大概是连着做这类型的题目,也可能是简单类的,现在可以在自己写的代码上跑通了。
重点,原始链表是有序的,升序。
所以只需要挨着判断是否相同就可以啦。
实现
my
我的解法里使用了两个辅助变量
里面空指针的问题处理不太好,运行了好几次都出错了
struct ListNode* deleteDuplicates(struct ListNode* head){
if (head == NULL){
return head;
}
struct ListNode *cur, *pre;
cur = head;
pre = cur->next;
while(cur && pre){
while(pre && cur->val == pre->val){
pre = pre->next;
}
cur->next = pre;
cur = pre;
if (pre){
pre = pre->next;
}
}
return head;
}
官方
struct ListNode* deleteDuplicates(struct ListNode* head){
if (head == NULL){
return head;
}
struct ListNode *cur;
cur = head;
while(cur && cur->next){
if (cur->val == cur->next->val){
cur->next = cur->next->next;
}else{
cur = cur->next;
}
}
return head;
}