LeetCode题解 week15

来源:互联网 发布:java第十版基础篇答案 编辑:程序博客网 时间:2024/05/16 02:14

82. Remove Duplicates from Sorted List II
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.

其中,结点ListNode的 定义如下:

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */

这题与83. Remove Duplicates from Sorted List有一些小差别,都是有一个已经排好序的链表,83题是要我们删除所有值重复的结点,使所有值只出现一次(1->1->2->3删为1->2->3),82题则是当一个值重复出现时,将全部值为该值的结点全部删去,只留全部不同的值的结点(1->1->2->3删为2->3)。

一种常见的思路为,使用循环,依此对链表中的每个结点进行判断和操作,当发现了一个值只出现了一次,把上一个只出现了一次的值的next指针指过来,指向新发现的只出现了一次的结点。如果没有只出现一次的结点,则返回一个NULL空指针。

为了方便处理,在输入的链表前面加了一个结点。参考代码如下:

class Solution {public:    ListNode* deleteDuplicates(ListNode* head) {        if(head == NULL || head->next == NULL)            return head;        ListNode* now = new ListNode(0);        ListNode* first = now;        now->next = head;        ListNode* next = head;        int count = 1;        while(next != NULL){            if(next->next == NULL || next->val != next->next->val){                if(count == 1) {                    now->next = next;                    now = now->next;                }                count = 1;            }            else {                count++;            }            next = next->next;         }        now->next = NULL;        return first->next;    }};

但其实这个问题也可以尝试使用递归来解决。使用循环略过所有重复的结点,当前不重复的结点的next指针指向递归求得的下一个不重复的结点。以后可以多考虑一下其他方法来解决问题。

class Solution {public:    ListNode* deleteDuplicates(ListNode* head) {        if(head == NULL || head->next == NULL)            return head;        int val = head->val;        ListNode* temp = head->next;        if(temp->val != val) {            head->next = deleteDuplicates(temp);            return head;        }        else {            while(temp != NULL && temp->val == val)                temp = temp->next;            return deleteDuplicates(temp);        }    }};
原创粉丝点击