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

Input/Output

풀이

// Singly-linked lists are already defined with this interface:
// class ListNode<T> {
//   ListNode(T x) {
//     value = x;
//   }
//   T value;
//   ListNode<T> next;
// }
//
ListNode <Integer> solution(ListNode<Integer> l, int k) {
    // 자료구조가 null 이면 바로 반환
    if (l == null) return l;
    
    // l 의 값이 k 와 같고
    // null 이 아닐 경우 while 반복
    while (l.value == k && l != null){
        l = l.next;
        
        if (l == null) break;
    }
    
    if (l == null) return l;

    ListNode c = l;

    while(c.next != null){
        if ((int)(c.next.value) == k) c.next = c.next.next;
        else c=c.next;
    }
    
    return l;
}