LeetCode 83. 删除排序链表中的重复元素(Remove Duplicates from Sorted List)

版权声明:转载请说明出处!!! https://blog.csdn.net/u012585868/article/details/83514591

题目描述

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

示例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) {
        while(!head){
            return head;
        }
        ListNode* first=head;
        ListNode* sec=head->next;
        while(sec!=NULL){
            if(first->val==sec->val){
                first->next=sec->next;
            }
            else{
                first=first->next;
            }
            sec=sec->next;
        } 
        return head; 
    }     
};

猜你喜欢

转载自blog.csdn.net/u012585868/article/details/83514591