Remove Duplicates from Sorted List

来源:互联网 发布:flash cs3 mac 中文 编辑:程序博客网 时间:2024/05/28 19:24

描述
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.
中文:按序排列的单链表,删除冗余元素。

分析:只要用两个指针,一个记录之前的结点,一个记录现在的结点,判断是否相同进行删除。

/** * 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==nullptr)  return nullptr;        for(ListNode * prev=head, *cur=head->next;cur;cur=cur->next)        {            if(cur->val==prev->val)            {                prev->next=cur->next;                delete cur;            }            else            {                prev=cur;            }        }        return head;    }};
0 0
原创粉丝点击