問題描述
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
補充說明:
給定一個排序過后的鏈表,將其中重復的值去掉,返回成功后的結果。
方案分析
- 如何判斷值是否重復?判斷兩個元素值是否重復,需要兩個指針,分別指向要比較的兩個元素。
- 如何比較?其實比較簡單,比較相鄰的兩個元素,如果值相同,則刪除后邊那個元素。
- 指針如何移動?如果比較的兩個元素的值相同,刪除后面那個元素后,將后面的那個指針后移,繼續比較;
如果比較的兩個元素的值不同,則同時后移兩個指針。
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 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