問題描述
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.
Subscribe to see which companies asked this question
補充說明:
給定一個排序過后的鏈表,將其中重復(fù)的值去掉观腊,返回成功后的結(jié)果邑闲。
方案分析
- 如何判斷值是否重復(fù)?判斷兩個元素值是否重復(fù)梧油,需要兩個指針苫耸,分別指向要比較的兩個元素。
- 如何比較儡陨?其實比較簡單褪子,比較相鄰的兩個元素,如果值相同迄委,則刪除后邊那個元素褐筛。
- 指針如何移動?如果比較的兩個元素的值相同叙身,刪除后面那個元素后渔扎,將后面的那個指針后移,繼續(xù)比較信轿;
如果比較的兩個元素的值不同晃痴,則同時后移兩個指針残吩。
python實現(xiàn)
# 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:
return []
cur_node = head
next_node = head.next
while(next_node):
if cur_node.val == next_node.val:
cur_node.next = next_node.next
else:
cur_node = cur_node.next
next_node = cur_node.next
return head