func insert(_ value: Int, _ index: Int) { let newNode = ListNode(value) guard let nodes = values else { values = [] values?.append(newNode) return } // index 越界 if index < 0 || index >= nodes.count { return } var temp: [ListNode] = [] for i in 0..<nodes.count { if i == index { temp.append(newNode) } temp.append(nodes[i]) } values = temp }
删除
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
func remove(at index: Int) { guard let nodes = values else { return } // 超出数组长度 if index < 0 && index >= nodes.count { return } var temp: [ListNode] = [] for i in 0..<nodes.count { if i != index { temp.append(nodes[i]) } } values = temp }
查找
1 2 3 4 5 6 7 8 9 10 11
func node(at index: Int) -> ListNode? { guard let nodes = values else { return nil } if index > 0 && index < nodes.count { return nodes[index] } return nil }