LeetCode题目之83-Remove Duplicates from Sorted List

题目描述如下:

Given a sorted linked list, delete all duplicates such that each element appear only once.

Example 1:

Input: 1->1->2
Output: 1->2
Example 2:

Input: 1->1->2->3->3
Output: 1->2->3

个人思路:

       思路很简单,一个有序链表,重复的数字必然是连续的。所以我们需要两个指针,一个first指针来找到重复的数字的起始位置,一个last指针来找到重复的数字所在节点指向的下一个位置。然后把两者链接起来即可,当然,如果于内存安全的角度考虑,我们当然需要把重复的节点所占的内存空间给释放掉,这里我就不再做过多的赘述,默认自行delete。

代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
ListNode* deleteDuplicates(ListNode* head) {
        if(head == NULL || head->next == NULL) return head; //若链表长度为0或1则直接返回
        ListNode* first = head,* last = head->next;
        while(last != NULL){
            if(first->val == last->val) last = last->next; //出现重复,last指针后移,此处应有delete
            else{ //开始无重复
                first->next = last; //舍弃中间
                first = last; //移动first指针到新的数字
                last = last->next; //last后移
            }
        }
        first->next = NULL; //first指针移动到最后一个无重复的数字之后下一个必然是NULL
        return head;
    }
发布了9 篇原创文章 · 获赞 0 · 访问量 1330

猜你喜欢

转载自blog.csdn.net/qq_41645895/article/details/102651803