每天一道LeetCode-16(删除排序链表中的重复元素)

29 阅读1分钟

题目描述

给定一个已排序的链表的头 head , 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。

示例 1:

输入: head = [1,1,2]
输出: [1,2]

示例 2:

输入: head = [1,1,2,3,3]
输出: [1,2,3]

分析

定义一个指针cur表示当前指向的节点,对这个原理的链表进行遍历,如果cur的next值等于cur的值,则让cur的next等于next的next,否则直接让cur指向next,当cur的next不存在时,遍历结束,返回head即可。

代码实现

struct ListNode* deleteDuplicates(struct ListNode* head){
    struct ListNode* cur = head;
    if(!head) return head;
    while(cur->next){
        if(cur -> val == cur -> next -> val){
            cur -> next = cur ->next ->next;
        }else{
            cur = cur -> next;
        }
    }
    return head;
}