1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| class Node { let val: Int var prev: Node?, next: Node? init(_ val: Int, prev: Node? = nil, _ next: Node? = nil) { self.val = val; self.prev = prev; self.next = next } }
class MyLinkedList { private let head: Node = Node(-1), tail: Node = Node(-1) private var count = 0
init() { head.next = tail; tail.prev = head }
func get(_ index: Int) -> Int { return findNode(index)?.val ?? -1 }
func addAtHead(_ val: Int) { addAtIndex(0, val) }
func addAtTail(_ val: Int) { addAtIndex(count, val) }
func addAtIndex(_ index: Int, _ val: Int) { if index >= 0 && index <= count, let node = findNode(index) { let newNode = Node(val) newNode.next = node newNode.prev = node.prev node.prev?.next = newNode node.prev = newNode count += 1 } }
func deleteAtIndex(_ index: Int) { if index >= 0 && index < count, let node = findNode(index) { node.prev?.next = node.next node.next?.prev = node.prev node.prev = nil; node.next = nil count -= 1 } }
private func findNode(_ index: Int) -> Node? { var p: Node?, i = 0 if index <= (count/2) { p = head.next while p != nil, i < index { p = p?.next; i += 1 } } else { p = tail; i = count while p != nil, i > index { p = p?.prev; i -= 1 } } return p }
private func printList() { var p = head.next, i: Int = 0 while p != nil, i < count { print(p!.val, terminator: "->" ) p = p?.next; i += 1 } print("") } }
|