LeetCode算法题82:删除排序链表中的重复元素 II解析

给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。

示例 1:

输入: 1->2->3->3->4->4->5
输出: 1->2->5

示例 2:

输入: 1->1->1->2->3
输出: 2->3

这个题主要是需要在出现重复时,将前一个不重复数的节点的next指向重复数字之后,所以可以新建一个前置指针,然后将前置指针的next作为cur指针开头,然后如果出现重复cur就一直向后移,直到找到不重复的,如果出现了重复,那么cur一定与前置指针的next不同,这时将前置指针的next指向cur的next,这样就跳过了所有的重复数,如果没出现重复,那么cur与前置指针的next相同,这时把前置指针向前移一个,继续把前置指针的next作为cur指针开头进行循环。

C++源代码:

/**
 * 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 || !head->next) return head;
        ListNode *dummy = new ListNode(-1), *pre = dummy;
        dummy->next = head;
        while(pre->next){
            ListNode *cur = pre->next;
            while(cur->next && cur->next->val==cur->val){
                cur = cur->next;
            }
            if(cur!=pre->next)
                pre->next = cur->next;
            else
                pre = pre->next;
        }
        return dummy->next;
    }
};

python3源代码:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head==None or head.next==None:
            return head
        dummy = ListNode(-1)
        pre = dummy
        dummy.next = head
        while pre.next:
            cur = pre.next
            while cur.next and cur.next.val==cur.val:
                cur = cur.next
            if cur!=pre.next:
                pre.next = cur.next
            else:
                pre = pre.next
        return dummy.next

猜你喜欢

转载自blog.csdn.net/x603560617/article/details/87815957
今日推荐