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

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

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

样例

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

标签

链表

思路

当前节点 current 的值若是与下一个节点的值相同,则向后遍历把与 current 相等的节点都找到,且跳过。若不相同,则将该节点放入已删除序列中。

code

/**
 * 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
        if(head == NULL || head->next == NULL) {
            return head;
        }
        ListNode *newHead = new ListNode(0);
        ListNode *next = newHead;
        ListNode *current = head;

        while(current != NULL) {
            if(current->next != NULL && current->val == current->next->val) {
                while(current->next != NULL && current->val == current->next->val) {
                    current = current->next;
                }
            }
            else {
                next->next = current;
                next = next->next;
            }
            current = current->next;
        }
        next->next = current;
        
        return newHead->next;
    }
};
原文地址:https://www.cnblogs.com/libaoquan/p/7172168.html