LeetCode算法系列:83. Remove Duplicates from Sorted List

版权声明:由于一些问题,理论类博客放到了blogger上,希望各位看官莅临指教https://efanbh.blogspot.com/;本文为博主原创文章,转载请注明本文来源 https://blog.csdn.net/wyf826459/article/details/82894224

题目描述:

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

算法实现:

和上一个问题极其类似82. Remove Duplicates from Sorted List II,将原来记录重复元素前一个元素的指针指向重复元素的第一个元素即可。

/**
 * 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) {
        if(head == NULL)return head;
        ListNode *p1, *p2;
        p1 = head;
        p2 = head;
        while(p1 -> next != NULL){
            p2 = p1;
            while(p1 -> next != NULL && p1 -> next -> val == p1 -> val){
                p1 = p1 -> next;
            }
            if(p1 -> next == NULL){
                p2 -> next = NULL;
                break;
            }
            p1 = p1 -> next;
            p2 -> next = p1;
                
        }
        return head;
    }
};

猜你喜欢

转载自blog.csdn.net/wyf826459/article/details/82894224