【LeetCode】Remove Duplicates from Sorted List系列

来源:互联网 发布:ubuntu 修改apt get源 编辑:程序博客网 时间:2024/06/05 10:07

83. Remove Duplicates from Sorted List

介绍

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.

题意: 删除链表中的重复元素, 有多个重复元素存在时候, 只需要保留一个就可以了.

解答

下面这个方法主要是先确定两个值不相等的节点, 如果节点之间的距离不等于1的话就删除中间的节点.

/** * 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)   return head;        ListNode *fast = head->next, *slow = head;        while(fast)        {            if(fast->val != slow->val && slow->next != fast)            {                ListNode *temp = slow->next;                slow->next = temp->next;                delete temp;            }else if(slow->val == fast->val)            {                fast = fast->next;            }else             {                slow = slow->next;                fast = fast->next;            }        }        while(slow->next != fast)        {            ListNode *temp = slow->next;            slow->next = temp->next;            delete temp;        }        return head;    }};

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.

题意: 删除所有的重复元素. 不同于上一道题的是, 如果链表中存在重复的值val, 那么所有值等于val的节点都要被删除.

解答

有两个要点:
1. 添加一个辅助节点作为头结点, 可以帮助我们处理头结点是重复值得问题.
2. 有两个指针pre指向最后一个有效节点, cur指向第一个和pre后一个节点值不等的节点,如果两者距离超过1, 说明pre后的节点是重复的, 我们只要从pre->next得到cur之前的所有链表节点.

class Solution {public:    ListNode* deleteDuplicates(ListNode* head)    {        if( !head || !(head->next) ) return head;        ListNode *newHead = new ListNode(0);        newHead->next = head;        ListNode *pre = newHead, *cur = head->next;        while(cur)        {            if( pre->next->val == cur->val)            {                cur = cur->next;            }            else if(pre->next->next == cur)            {                pre = pre->next;                cur = cur->next;            }else   //删除从pre->next得到cur之前的所有链表节点            {                pre->next = cur;                cur = cur->next;            }        }        if(pre->next->next != cur)        {            pre->next = cur;        }        return newHead->next;    }  };
阅读全文
0 0
原创粉丝点击