美文网首页
LeetCode 83. 删除排序链表中的重复元素

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

作者: SmallRookie | 来源:发表于2018-12-26 14:25 被阅读6次

题目描述

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

示例 1:

输入: 1->1->2
输出: 1->2

示例 2:

输入: 1->1->2->3->3
输出: 1->2->3

题解

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        ListNode* l = head, *tmp;
        if(l == NULL) return l;
        while(l->next != NULL) {
            tmp = l->next;
            if(l->val == tmp->val) {
                l->next = tmp->next;
                free(tmp);
            } else {
                l = l->next;
            }
        }
        return head;
    }
};

相关文章

网友评论

      本文标题:LeetCode 83. 删除排序链表中的重复元素

      本文链接:https://www.haomeiwen.com/subject/cvehlqtx.html