[LeetCode]题解(python):083 - Remove Duplicates from Sorted List

时间:2022-01-23 01:06:51

题目来源


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.


题意分析


Input:

:type head: ListNode

Output:

:rtype: ListNode

Conditions:一个有序list,删除掉重复的元素


题目思路


每次判断增加一个节点时,看是否与当前结点重复,重复则跳过


AC代码(Python)

 # 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 head == None or head.next == None:
return head
p = head
while p.next != None:
if p.val == p.next.val:
p.next = p.next.next
else:
p = p.next
return head