版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a786150017/article/details/82956323
83. Remove Duplicates from Sorted List
题目描述
移除有序链表的重复结点
例子
Example 1:
Input: 1->1->2
Output: 1->2
Example 2:
Input: 1->1->2->3->3
Output: 1->2->3
解法
看到链表题,想到递归。
刚开始想用非递归写,发现有点绕。
[解法1] - 递归解法
[解法2] - 非递归,参照递归的思想
解法1
递归,截止条件-链表为空/只有一个元素。判断head和head.next是否相等,若相等,递归操作head.next;否则, 返回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
if head.val == head.next.val:
return self.deleteDuplicates(head.next)
head.next = self.deleteDuplicates(head.next)
return head
解法2
非递归,将递归改造成非递归。外面套一层while, 内部p = p.next.
为代码简洁起见,引入dummy指针pNode
# 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):
if not head or not head.next:
return head
pNode = ListNode(-1)
pHead = pNode
p = head
while p:
while p.next and p.val == p.next.val:
p = p.next
pNode.next = p
pNode = pNode.next
p = p.next
return pHead.next