본문 바로가기
CodeSignal/Interview Practice

[Linked Lists] removeKFromList

by 벤진[Benzene] 2020. 5. 30.

Problem:

Note: Try to solve this task in O(n) time using O(1) additional space, where n is the number of elements in the list, since this is what you'll be asked to do during an interview.

Given a singly linked list of integers l and an integer k, remove all elements from list l that have a value equal to k.

 

Example

  • For l = [3, 1, 2, 3, 4, 5] and k = 3, the output should be
    removeKFromList(l, k) = [1, 2, 4, 5];
  • For l = [1, 2, 3, 4, 5, 6, 7] and k = 10, the output should be
    removeKFromList(l, k) = [1, 2, 3, 4, 5, 6, 7].

-Summary-

1. Create a temporary head for the case being first number = k (Then connect with original linked list l)

2. Loop through the linked list if k faced, we point the next to next.next. (Skip the value)

3. After finish the loop, return after temp_head.next

 

사람들이 푼 답을 보니, 다음과 같이 temp head 를 만들지 않고 푼 방법도 있었다. Linked List 는 아직 익숙하지가 않아서 공부를 많이 해야 할 것 같다.

def removeKFromList(l, k):
    c = l
    while c:
        if c.next and c.next.value == k:
            c.next = c.next.next
        else:
            c = c.next
    return l.next if l and l.value == k else l

모든 문제에 대한 저작권은 CodeSignal 회사에 있습니다. [Copyright © 2020 BrainFights Inc. All rights reserved]

https://codesignal.com/

댓글