728x90
문제
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
}
}
728x90
'Algorithm > LeetCode' 카테고리의 다른 글
LeetCode - Running Sum of 1d Array (0) | 2020.08.30 |
---|---|
LeetCode - Detect Capital (0) | 2020.08.07 |
💯 Daily LeetCode Challenge Day_19 - Add Binary (0) | 2020.07.29 |
💯 Daily LeetCode Challenge Day_18 - Course Schedule 2 (0) | 2020.07.24 |
💯 Daily LeetCode Challenge Day_17 - Top K Frequent Elements (0) | 2020.07.18 |
댓글