본문 바로가기
Leetcode

[LeetCode] Remove Duplicates from Sorted List 파이썬 (Linked List, shallow copy, deepcopy)

by YGSEO 2021. 3. 31.
728x90

하위 95% 솔루션 😱

64ms

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        total = []
        while head:
            total.append(head.val)
            head = head.next
        total = list(sorted(set(total)))
        print(total)

        answer = None

        for i in range(len(total)):
            if i == 0:
                answer = ListNode(total[i])
            else:
                new_node = ListNode(total[i])
                curr_node = answer
                while curr_node.next != None: # fill all the curr_node's next
                    curr_node = curr_node.next
                curr_node.next = new_node # insert new_node to curr_node.next
        return answer

# output 
# 1 -> 2 -> 3 -> None

상위 20% 솔루션

40ms


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        dummy = ListNode(0.1, head) # start point
        cur = dummy # copy dummy to cur to manipulate
        while cur.next:
            if cur.val == cur.next.val:
                cur.next = cur.next.next
            else:
                cur = cur.next
        return dummy.next # return original from start point.

 


singly linked list 이해 완료 !

class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

    def __repr__(self):
        if self:
            return "{} -> {}".format(self.val, self.next)

start = None
dummy = myNode = ListNode(start)
head = [1,1,2,3,3]
# insert head to myNode # for debugging
while head:
    myNode.next = ListNode(head[0])
    myNode = myNode.next
    head.pop(0)

print("myNode\t\t:",dummy.next)
print("my last node:",myNode.next)

# Output
# myNode      : 1 -> 1 -> 2 -> 3 -> 3 -> None
# my last node: None

dummy를 만들어줘서 copy를 사용해서 return을 해야한다.

(myNode를 바로 return 할 경우 myNode의 맨 마지막 노드부터 return이 되기 때문에 None을 return하게 되기 때문)

 

노드에 data insert

pop을 사용해서 head에 있는 element를 하나씩 myNode의 next로 넣어주면서 myNode의 시작점을 다시 myNode.next로 업데이트 해주기

 

 


__repr__ 메서드 관련 자료 출처: shoark7.github.io/programming/python/difference-between-__repr__-vs-__str__ 

 

deep-copy & shallow copy : wikidocs.net/16038 

 

singly-linked list : wikidocs.net/34315

 

728x90

댓글