Description
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.
给定一个排序链表,删除所有重复的元素使得每个元素只留下一个。
案例:
给定 1->1->2,返回 1->2
给定 1->1->2->3->3,返回 1->2->3
Solution
判断当前值与下一个值是否相同,相同则修改节点的next
指向下一个节点的next
。重复判断。注意判断指针是否为空。
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 18 10:57:00 2018
@author: Saul
"""
# 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
"""
if head == None or head.next == None:
return head
p = head
while p:
while p.next and p.val == p.next.val:
p.next = p.next.next
p = p.next
return head