Leetcode 83 删除排序链表中的重复元素 Python C++ 史上最详细题解系列

鸽了好几天了,结果这道题又这么水。。。

但还是写下,一步一个脚印来。

每天更新一道python or C++ leetcode题,力求讲解清晰准确,客官们可以点赞或者关注。

题目:

给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。

示例 1:

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

示例 2:

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

思路应该说是不难的,要注意,这里是排序好了的链表。所以相同的元素会在一起。

当你检测到你当前指针的值与下一项相同时,说明你应该进行删除操作。删除就是一个while循环检测需不需要删除,需要就删。

Python

# 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
        """
        i = head#头部指针
        if not i:
            return head
        while i.next is not None:#当i的下一项存在时
            while i.next is not None and i.next.val == i.val:#有重复项的话
                i.next = i.next.next#删除
            i = i.next#比如1->1->2,会删掉中间的1,然后这一步i跳到2
            if not i:
                break
        return head

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) return head;
        ListNode* p = head;
        while (p && p->next){
            while (p->next && p->next->val == p->val){
                p->next = p->next->next;
            }
            p = p->next;
        }
        return head;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_41958153/article/details/82050512
今日推荐