func searchNode(index: Int) -> Node<T>? {
var indexNode = head
for _ in 0..<index {
indexNode = indexNode?.next
}
return indexNode
}
func insert(data: T, index: Int) {
var previousNode: Node<T>?
var indexNode: Node<T>?
let newNode = Node<T>(data: data)
if index > self.index || isEmpty {
append(data: data)
return
} else if index == self.index {
previousNode = tail?.previous
indexNode = Node<T>(data: data)
previousNode?.next = indexNode
indexNode?.next = tail
} else if index == 0 {
head?.previous = newNode
newNode.next = head
head = newNode
} else {
indexNode = searchNode(index: index)
previousNode = indexNode?.previous
previousNode?.next = newNode
newNode.previous = previousNode
newNode.next = indexNode
indexNode?.previous = newNode
}
self.index += 1
}
index > self.index || isEmpty
리스트가 비어있거나, 원하는 인덱스보다 큰 경우는 append 이용index == self.index
리스트의 마지막 인덱스에 넣는 경우index == 0
기존 head를 뒤로 밀어내고 들어가는 경우func removeAt(index: Int) -> T? {
guard !isEmpty else { return nil }
guard index >= self.index else {
let indexNode = searchNode(index: index)
indexNode?.previous?.next = indexNode?.next
indexNode?.next?.previous = indexNode?.previous
return indexNode?.data
}
guard index != self.index else {
let data = tail?.data
tail?.previous?.next = nil
tail = tail?.previous
return data
}
return nil
}
index < self.index
index == self.index