leetcode:Remove Duplicates from Sorted List II (留下链表中只出现一次的元素)【面试算法题】

来源:互联网 发布:php pdf完整版 编辑:程序博客网 时间:2024/04/30 22:42

题目:

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

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

题意要把链表中有重复的元素全部去除,只留下没有重复过的元素。



依旧是链表的操作,用pre和now去删除节点,由于头节点也有可能删除,因此先建一个Head节点连头节点。

pre从Head开始,用now去判断是否重复。

如果重复,循环到下一个不同元素之前,把之间的相同元素直接跳过。

再向前移动pre和now指针。

/** * 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 *pre,*now,*Head;        if(!head||!head->next)return head;        Head=new ListNode(-1);        Head->next=head;        pre=Head;        now=head;        while(now&&now->next)        {            if(now->val == now->next->val)            {                while(now->next && now->val == now->next->val)                {                    now=now->next;                }                pre->next=now->next;                now=now->next;            }            else             {                pre=now;                now=now->next;            }        }        head=Head->next;        delete(Head);        return head;    }};// blog.csdn.net/havenoidea

题解目录

原创粉丝点击