编程语言
首页 > 编程语言> > LeetCode83. Remove Duplicates from Sorted List(C++)

LeetCode83. Remove Duplicates from Sorted List(C++)

作者:互联网

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

解题思路:双指针法

/**
 * 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 *p=new ListNode(99999),*q=head;
        p->next=head;
        head=p;
        while(q!=NULL){
            if(p->val==q->val){
                p->next=q->next;
                free(q);
                q=p->next;
            }
            else{
                p=p->next;
                q=q->next;
            }
        }
        return head->next;
    }
};

 

标签:head,ListNode,val,Duplicates,List,LeetCode83,next,Input,NULL
来源: https://blog.csdn.net/qq_41562704/article/details/86669033