How to reverse the Linked List in Swift extension? -


i want reverse single linked list in extension, it's failed.can 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 linked list.  extension list {      func reverse() {       }  } 

i have solution here. please read comments, evident code too. have added 'description' via customstringconvertible list debugging , 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, , reverse link until visit last node in list.         // once reach end, items except last 1 have         // 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 last item in list has links reversed.         currentnode?.nextitem = prevnode          return currentnode      }  }  var list = list(1,2,3,5)  print(list ?? "failed create list")   if let reversed = list.reverse(){   print(reversed) } 

Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -