kodecocodes/swift-algorithm-club

Any way to reverse Linklist output in Swift

ashishsme14 opened this issue · 0 comments

We need to write swift code using Link List. Conditions are -

func insert(data:Int) insert data to the list and return nothing.
count:Int keep track of the number of the nodes in the link
head:Node holds the first element reference. Just implement inset() and count.

Question

We had written as -

import Foundation
--- Editable Code ---
class Node {
    var data : Int
    var next : Node? = nil
    init(_ data: Int) {
        self.data = data
    }
}

class LinkedList {
    var count : Int = 0;
    var head : Node? = nil
    func insert(data: Int) -> Void {
        let next : Node? = head
        head = Node(data)
        head?.next = next
        count += 1
    }
}

--- End Editable Code ---
--- Un Editable Code  ---
let stdout = ProcessInfo.processInfo.environment["OUTPUT_PATH"]!
FileManager.default.createFile(atPath: stdout, contents: nil, attributes: nil)
let fileHandle = FileHandle(forWritingAtPath: stdout)!
guard let arrCount = Int((readLine()?.trimmingCharacters(in: .whitespacesAndNewlines))!)
else { fatalError("Bad input") }
var list = LinkedList()
if arrCount>0{
for _ in 1...arrCount {
    guard let arrItem = Int((readLine()?.trimmingCharacters(in: .whitespacesAndNewlines))!)
    else { fatalError("Bad input") }
   list.insert(data:arrItem)
}
}
let count = list.count
fileHandle.write(String(count).data(using: .utf8)!)
var temp:Node! = list.head
while temp != nil {
     fileHandle.write("\n".data(using: .utf8)!)
    fileHandle.write(String(temp.data).data(using: .utf8)!)
    temp = temp.next
}
--- End Un Editable Code ---

We getting output as -

Input as 5 1 2 3 4 5

Our Output as 5 5 4 3 2 1

Expected Output as 5 1 2 3 4 5