Reverse Doubly Link List.

[Question] Given a Doubly Linked List, the task is to reverse the given Doubly Linked List.

Here we can can solve by two approach #1 Iterative #2 Recursive

public class DoublyLinkedListNode<T> {
    var item: T
    var next: DoublyLinkedListNode?
    weak var previous: DoublyLinkedListNode?
    
    public init(item: T) {
        self.item = item
    }
}
// MARK: - Reverse Doubly linked list
public func reverse() {
    //        var node = head
    //        while let currentNode = node {
    //            node = currentNode.next
    //            swap(&currentNode.next, &currentNode.previous)
    //            head = currentNode
    //        }
    // Or
    var node = head
    while let currentNode = node {
        node = currentNode.next
        let nxt = currentNode.next
        let pvs = currentNode.previous
        currentNode.next = pvs
        currentNode.previous = nxt
        head = currentNode
    }
}

func reverseListRecursive(_ head: DoublyLinkedListNode<T>?) -> DoublyLinkedListNode<T>? {
    if head == nil || head?.next == nil {
        return head
    }
    let temp = reverseListRecursive(head?.next)
    head?.next?.next = head
    head?.previous = head?.next
    head?.next = nil
    return temp
}

For information about usage visit my Githhub Page

Leave a Comment

Your email address will not be published. Required fields are marked *