谷歌 iOS 职位店面

Questions:

  • First some Swift related questions mainly on Sequence and IteratorProtocol types
  • Design a Linked List that can be iterated into (this was for a mobile iOS - Swift based position so i.e using Sequence and IteratorProtocol):
protocol Sequence {
	associatedtype Iterator: IteratorProtocol

	func makeIterator() -> Iterator
}

protocol IteratorProtocol {
	associatedtype Element

	mutating func next() -> Element?
}

eg.

// given some head on a linked list node
// 1 -> 2 -> 3 ->

for num in head {
print(num) // 1, 2, 3
}

我的代码

class LinkedListNode<T> {
	let value: T
	var next: LinkedListNode?

	init(_ value: T) {
		self.value = value
    }
}

extension LinkedListNode: Sequence {
   func makeIterator() -> Iterator {
		return LinkedListIterator(self)
   }
}

class LinkedListIterator<T>: IteratorProtocol {
	var current: LinkedListNode
	
	init(_ node: LinkedListNode<T>) {
        self.current = node
	}

    func next() -> T? {
	    let result = current
	    current = current.next
	    return result.value
    }
}