Skip to content

Instantly share code, notes, and snippets.

@ashalva
Last active May 9, 2018 06:39
Show Gist options
  • Save ashalva/41e03a03e8e0af2d77d098c7f7464752 to your computer and use it in GitHub Desktop.
Save ashalva/41e03a03e8e0af2d77d098c7f7464752 to your computer and use it in GitHub Desktop.
Reversing doubly linked list in swift.
class Node<T> {
var value:T
var next: Node?
var previous: Node?
init(value: T) {
self.value = value
self.next = nil
self.previous = nil
}
}
//Reversing doubly linked list
func reverseDoublyLinkedList(head: Node<Int>) -> Node<Int>? {
var h: Node<Int>? = head
var temp: Node<Int>? = nil
var current: Node<Int>? = h
while current != nil {
temp = current!.previous
current!.previous = current!.next
current!.next = temp
current = current!.previous
}
if temp != nil {
h = temp?.previous
}
return h
}
//test
let head = Node(value: 1)
let second = Node(value: 2)
let third = Node(value: 3)
let fourth = Node(value: 4)
head.next = second
second.previous = head
second.next = third
third.previous = second
third.next = fourth
fourth.previous = third
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment