Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Input: 1->1->2
Output: 1->2
Example 2:
Input: 1->1->2->3->3
Output: 1->2->3
直接遍历链表,依次判断即可。注意在指针后移之前,要先判断当前的val和next.val是否相等,不相等才能后移,否则不能处理连续2个以上的duplicates。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
l = head
while l:
if not l.next:
return head
if l.val == l.next.val:
if not l.next.next:
l.next = None
return head
l.next = l.next.next
if l.val != l.next.val:
l = l.next