Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions arai60/remove_duplicates_from_sorted_list_2/phase1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
class Solution:
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummy_head = ListNode(0)
current_head = dummy_head
skip_number = None
while head:
if head.next and head.val != head.next.val and head.val != skip_number:
current_head.next = ListNode(head.val)
current_head = current_head.next
elif head.next == None and head.val != skip_number:
current_head.next = ListNode(head.val)
skip_number = head.val
head = head.next
return dummy_head.next
25 changes: 25 additions & 0 deletions arai60/remove_duplicates_from_sorted_list_2/phase2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
"""
Reference:
fhiyoさん: https://github.com/fhiyo/leetcode/pull/4/files
nittocoさん: https://github.com/nittoco/leetcode/pull/9/files
TORUさん: https://github.com/TORUS0818/leetcode/pull/6/files
phase1の回答は, skip_numberという状態変数を持って条件を制御していくやりかただったが, 状態変数の扱いが難しいものになる恐れがあると考えた。
あまり状態変数は持ちたくないものではあるので, 重複が見つかったらスキップというやり方を採用する。
"""

class Solution:
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
def skip_duplicate_nodes(node):
while node.next and node.val == node.next.val:
node = node.next
return node
dummy_head = ListNode(-1)
current_node = dummy_head
while head:
if head.next and head.val == head.next.val:
head = skip_duplicate_nodes(head)
else:
current_node.next = ListNode(head.val)
current_node = current_node.next
head = head.next
return dummy_head.next
16 changes: 16 additions & 0 deletions arai60/remove_duplicates_from_sorted_list_2/phase3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
class Solution:
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
def skip_duplicated_nodes(head: Optional[ListNode]) -> Optional[ListNode]:
while head.next and head.val == head.next.val:
head = head.next
return head
dummy_head = ListNode(-1)
current_node = dummy_head

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

個人的にはcurrent_nodeは今注目しているもの(今回であれば重複判定とかするポインタ)の名前にする方が分かりやすいかなと思いました。
本コードではheadが使われてますね。

while head:
if head.next and head.val == head.next.val:
head = skip_duplicated_nodes(head)
else:
current_node.next = ListNode(head.val)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ListNode()で新たにオブジェクトを作らなくてもheadの繋ぎかえでいけると思います。

current_node = current_node.next
head = head.next
return dummy_head.next