Robin.Chao
Robin.Chao

Reputation: 113

How to reverse the Linked List in Swift extension?

I want to reverse the Single Linked List in extension, but finally it's failed.can someone help me? thanks.

   public class List<T: Equatable> {
        var value: T!
        var nextItem: List<T>?

   public convenience init!(_ values: T...) {
        self.init(Array(values))
   }

   init!(var _ values: Array<T>) {
        if values.count == 0 {
            return nil
        }
        value = values.removeFirst()
        nextItem = List(values)
     }
 }



 // Reverse a linked list.
 extension List {
     func reverse() {

     }
 }

Upvotes: 4

Views: 1883

Answers (1)

Shripada
Shripada

Reputation: 6522

I have a solution here. Please read the comments, its all evident from the code too. Also I have added a 'description' via CustomStringConvertible to the list to help debugging and printing.

public class List<T: Equatable>{
    var value: T!
    var nextItem: List<T>?

    public convenience init!(_ values: T...) {
        self.init(Array(values))
    }

    init!(_ values: Array<T>) {
        if values.count == 0 {
            return nil
        }
        var valuesCopy = values
        value = valuesCopy.removeFirst()
        nextItem = List(Array(valuesCopy))
    }



}

extension List : CustomStringConvertible{
    public var description: String {
        var desc = String()
        var listRef : List<T>? = self
        while listRef != nil {
            desc += "\((listRef?.value)!) "
            listRef = listRef?.nextItem
        }
        return desc
    }
}

extension List{
    func reverse() -> List?{

        // Iterate through each item, and reverse its link until you visit the last node in the list.
        // Once you reach the end, All items except the last one would have
        // their links reversed.
        var nextNode : List<T>? = self.nextItem
        var prevNode : List<T>? = nil
        var currentNode : List<T>? = self

        while nextNode != nil{

            currentNode?.nextItem = prevNode
            prevNode = currentNode
            currentNode = nextNode
            nextNode =  currentNode?.nextItem
        }

        //Ensure the last item in the list too has its links reversed.
        currentNode?.nextItem = prevNode

        return currentNode

    }

}

var list = List(1,2,3,5)

print(list ?? "Failed to create the list")


if let reversed = list.reverse(){
  print(reversed)
}

Upvotes: 4

Related Questions