83. Remove Duplicates from Sorted List [easy] (Python)

题目链接

https://leetcode.com/problems/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.

题目翻译

给定一个有序链表,删除重复元素使每个元素之出现一次。

思路方法

思路一

遍历所有节点,对于每个节点,检查其后的一个节点是否与当前节点值相同,若相同则删除后面的节点。循环下去。

代码

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

class Solution(object):
    def deleteDuplicates(self, head):
        """ :type head: ListNode :rtype: ListNode """
        p = head
        while p:
            if p.next and p.next.val == p.val:
                p.next = p.next.next
            else:
                p = p.next
        return head

思路二

遍历所有节点,对于每个节点,从后一个节点开始一个个检查是否与当前节点值相同,直到找到一个后面的节点其值与当前节点不同,删除中间的所有与当前节点值相同的节点。循环下去。

代码

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

class Solution(object):
    def deleteDuplicates(self, head):
        """ :type head: ListNode :rtype: ListNode """
        p = q = head
        while p:
            while q and q.val == p.val:
                q = q.next
            p.next = q
            p = q
        return head

思路三

递归实现,本质上是从后向前检查是否有相同的节点。

代码

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

class Solution(object):
    def deleteDuplicates(self, head):
        """ :type head: ListNode :rtype: ListNode """
        if not head or not head.next:
            return head
        head.next = self.deleteDuplicates(head.next)
        return head if head.val != head.next.val else head.next

PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.csdn.net/coder_orz/article/details/51506143

    原文作者:coder_orz
    原文地址: https://blog.csdn.net/coder_orz/article/details/51506143
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞