LintCode-删除排序链表中的重复数字 II

给定一个排序链表,删除所有重复的元素只留下原链表中没有重复的元素。

您在真实的面试中是否遇到过这个题?
  Yes



样例

给出1->2->3->3->4->4->5->null,返回1->2->5->null

给出1->1->1->2->3->null,返回 2->3->null

标签 Expand  

分析:因为是排序链表,所以每次判断和后面的是不是一样就行,一样就一直把这个相同的遍历到不同的点

代码:

/**
 * Definition of ListNode
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */
class Solution{
public:
    /**
     * @param head: The first node of linked list.
     * @return: head node
     */
    ListNode * deleteDuplicates(ListNode *head) {
        // write your code here
        ListNode dummy(-1);
        ListNode* temp = &dummy;
        while(head)
        {
            if(head->next)
            {
                bool same = false;
                while(head->next&&head->next->val==head->val)
                {
                    same = true;
                    head = head->next;
                }
                if(!same)
                {
                    temp->next = new ListNode(head->val);
                    temp = temp->next;
                }
                head = head->next;
            }
            else
            {
                temp->next = head;
                head = head->next;
            }
        }
        return dummy.next;
    }
};
    原文作者:LintCode题目解答
    原文地址: https://blog.csdn.net/wangyuquanliuli/article/details/47359057
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞