반응형
1. Swift
1-1. My Solution
enum LinkedError : Error {
case nilError
case lessLength
}
class Node {
var data: Int
var next: Node?
init(_ data: Int) {
self.data = data
}
}
func frontBackSplit(source: Node?, front: inout Node?, back: inout Node?) throws {
guard let _source = source else {
throw LinkedError.nilError
}
var isNilBreak = false
var currentNode : Node? = _source
var nodeIntValue : [Int] = []
while !isNilBreak {
nodeIntValue.append(currentNode!.data)
if currentNode?.next == nil {
isNilBreak = true
}else{
currentNode = currentNode?.next
}
}
guard !(nodeIntValue.count < 2) else {
throw LinkedError.lessLength
}
let frontLength = Int(ceil(Double(nodeIntValue.count) / 2))
let testNodeArr = buildListFromArray([1, 2])
var firstNodeTemp : Node?
var secondNodeTemp: Node?
for i in 0 ..< frontLength {
nodeInsert(node: &firstNodeTemp, data: nodeIntValue[i])
}
for i in frontLength ..< nodeIntValue.count {
nodeInsert(node: &secondNodeTemp, data: nodeIntValue[i])
}
front = firstNodeTemp
back = secondNodeTemp
}
private func nodeInsert(node : inout Node?, data : Int) {
guard node != nil else {
node = .init(data)
return
}
if let _ = node?.next {
nodeInsert(node: &node!.next, data: data)
}else{
node?.next = .init(data)
}
}
1-2. Best Solution
extension Int : Error {}
class Node {
var data: Int
var next: Node?
init(_ data: Int) {
self.data = data
}
}
func frontBackSplit(source: Node?, front: inout Node?, back: inout Node?) throws {
guard source?.next != nil else {throw 1}
front = source
back = source
while back!.next?.next != nil
{
front = front!.next
back = back!.next!.next
}
back = front!.next
front!.next = nil
front = source
return
}
반응형
'Codewars(알고리즘) > 5Kyu' 카테고리의 다른 글
[Codewars] [5Kyu] Consecutive k-Primes (0) | 2024.11.30 |
---|---|
[Codewars] [5Kyu] Diophantine Equation (0) | 2023.07.17 |
[Codewars] [5kyu] Resistor Color Codes, Part 2 (수정중) (0) | 2021.01.26 |
[Codewars] [5kyu] Product of consecutive Fib numbers (0) | 2021.01.26 |