#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
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
"""
if head == None or head.next == None:
return head
ret = head
cur = head
head = head.next
while head != None:
if head.val != cur.val:
cur.next = head
cur = cur.next
head = head.next
cur.next = None
return ret
if __name__ == "__main__":
s = Solution()
head = ListNode(1)
t = head
for i in [1,2,2,3,3,5,6]:
t.next = ListNode(i)
t = t.next
t.next = None
t = head
while t != None:
print t.val
t = t.next
t = s.deleteDuplicates(head)
while t != None:
print t.val
t = t.next
78 leetcode - Remove Duplicates from Sorted List
最新推荐文章于 2024-09-18 20:11:15 发布