public class LinkedListNode<T> {
var value: T
var next: LinkedListNode?
weak var previous: LinkedListNode?
public init(value: T) {
self.value = value
}
}
public class LinkedList<T> {
public typealias Node = LinkedListNode<T>
private var head: Node?
public var isEmpty: Bool {
return head == nil
}
public var first: Node? {
return head
}
public var last: Node? {
guard var node = head else {
return nil
}
while let next = node.next {
node = next
}
return node
}
public func node(atIndex index: Int) -> Node {
if index == 0 {
return head!
} else {
var node = head!.next
for _ in 1..<index {
node = node?.next
if node == nil {
break
}
}
return node!
}
}
public func append(value: T) {
let newNode = Node(value: value)
if let lastNode = last {
newNode.previous = lastNode
lastNode.next = newNode
} else {
head = newNode
}
}
public var count: Int {
guard var node = head else {
return 0
}
var count = 1
while let next = node.next {
node = next
count += 1
}
return count
}
}
let list = LinkedList<String>()
list.append(value: "Hello")
list.append(value: "Hi")
list.append(value: "good")
print(list.isEmpty, list.first!.value, list.last!.value)
print(list.node(atIndex: 1).value)
print(list.count)
func stringAsInt(stringArray: [String]) -> [Int] {
let intArray1 = [0,1,2,3,4,5,6,7,8,9]
let string1 = ["0","1","2","3","4","5","6","7","8","9"]
var string2:[Int] = Array(repeating: 0, count: stringArray.count)
for k in 0..<stringArray.count {
for i in 0..<string1.count {
if stringArray[k] == string1[i] {
string2[k] = intArray1[i]
}
}
}
return string2
}
func arrayAdd(a: [Int]) -> Int {
var add = 0
if a.count <= 12 {
let int2 = [1, 10, 100, 1000, 10000, 100000, 1000000,
10000000, 100000000, 1000000000, 10000000000, 100000000000]
for i in 0..<a.count{
add += a[i] * int2[a.count - i - 1]
}
return add
}else {
for i in 0..<a.count {
var 倍数 = 1
var 次数 = 0
for _ in 0..<a.count - 1 - i {
次数 = 10 * 倍数
倍数 = 次数
}
add += a[i] * 倍数
}
}
return add
}
let array = [7,8,9,1,7,6,3,4,2,2]
print(arrayAdd(a: stringAsInt(stringArray: ["5","7","6"])))