Skip to content

Instantly share code, notes, and snippets.

@AdrianFerreyra
Last active October 31, 2017 18:54
Show Gist options
  • Save AdrianFerreyra/9d5ee622a84b397df776901e9402d377 to your computer and use it in GitHub Desktop.
Save AdrianFerreyra/9d5ee622a84b397df776901e9402d377 to your computer and use it in GitHub Desktop.
Return the head node of the singly linked list with each pair of nodes swapped. If there is a last odd node leave it in place. Example: Input: 1 -> 2 -> 3 -> 4 -> 5 Output: 2 -> 1 -> 4 -> 3 -> 5
enum LinkedList {
case empty
indirect case node(T, LinkedList)
func swapTwoFirst() -> LinkedList {
switch self {
case .node(let value, .node(let nextValue, let next)):
return .node(nextValue, .node(value, next.swapTwoFirst()))
case .empty:
return .empty
case .node(let value, .empty):
return .node(value, .empty)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment