C++ describes LeetCode83. Delete duplicate elements in the sorted list

C++ describes LeetCode83. Delete duplicate elements in the sorted list

  Hello everyone, my name is qí guān jié (qí guān jié). I record the learning process in CSDN. Time flies, the future can be expected, come on. Bloggers currently only blog in CSDN, and the only blog update address is: Qí guān jié ’s blog

This article was originally written by Qiguanjie. Please support the original article. Some platforms have been maliciously stealing bloggers' articles! ! !


Given a sorted linked list, delete all duplicate elements so that each element appears only once.

Example 1:

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

Example 2:

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

answer

Traverse from the beginning, if two adjacent ones are equal, delete the next node, otherwise continue to move right.

/**
 * 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*p = head;
        while(p->next){
    
    
            // 如果当前的和下一个一样,那么删除下一个结点,当前结点不动
            if(p->val == p->next->val){
    
    
                p->next = p->next->next;
            }else{
    
    
                // 如果不同,则继续移动
                p =p->next;
            }
        }
        return head;
    }
};

Guess you like

Origin blog.csdn.net/qq_43422111/article/details/109253233