Last active
May 9, 2018 06:39
-
-
Save ashalva/41e03a03e8e0af2d77d098c7f7464752 to your computer and use it in GitHub Desktop.
Reversing doubly linked list in swift.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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