본문 바로가기
Algorithm/LeetCode

💯 Daily LeetCode Challenge Day_20 - Remove Linked List Elements

by HaningYa 2020. 7. 29.
728x90

 

 

Explore - LeetCode

LeetCode Explore is the best place for everyone to start practicing and learning on LeetCode. No matter if you are a beginner or a master, there are always new topics waiting for you to explore.

leetcode.com


문제

Remove all elements from a linked list of integers that have value val.

Example:

Input: 1->2->6->3->4->5->6, val = 6 Output: 1->2->3->4->5


Swift 로 풀려니 Optional 처리가 걸린다.

while loop

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public var val: Int
 *     public var next: ListNode?
 *     public init() { self.val = 0; self.next = nil; }
 *     public init(_ val: Int) { self.val = val; self.next = nil; }
 *     public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
 * }
 */
class Solution {
    func removeElements(_ head: ListNode?, _ val: Int) -> ListNode? {
        let answer = ListNode(0)
        answer.next = head
        var cur: ListNode? = head
        var pre: ListNode? = answer
        
        while cur != nil {
            if cur?.val == val {
                pre?.next = cur?.next
            }else{
                pre = pre?.next
            }
            cur = cur?.next
        }
        return answer.next
    }
}

 

recursive

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public var val: Int
 *     public var next: ListNode?
 *     public init() { self.val = 0; self.next = nil; }
 *     public init(_ val: Int) { self.val = val; self.next = nil; }
 *     public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
 * }
 */
class Solution {
    func removeElements(_ head: ListNode?, _ val: Int) -> ListNode? {
        if head == nil {
            return nil
        }
        print(head?.val)
        head?.next = removeElements(head?.next, val)
        return head?.val == val ? head?.next : head
    }
}

 

Source

 

728x90

댓글