第十二周:83. Remove Duplicates from Sorted List

    xiaoxiao2021-03-25  68

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

    For example, Given 1->1->2, return 1->2. Given 1->1->2->3->3, return 1->2->3.

    这道题就是将当前结点与下一个结点进行比较,如果相等那么将当前结点的下一个结点删除,如果不相等,当前结点指向下一个结点。

    AC:

    /** * 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||head->next==NULL) return head; ListNode *p=head; ListNode *q=p->next; ListNode *temp; while(p&&q) { if(p->val==q->val) { temp=q; p->next=q->next; q=q->next; delete temp; } else { p=p->next; q=q->next; } } return head; } };

    转载请注明原文地址: https://ju.6miu.com/read-33937.html

    最新回复(0)