tensorflow / swift

Swift for TensorFlow
https://tensorflow.org/swift
Apache License 2.0
6.12k stars 608 forks source link

Any way to reverse Swift Link List Output #605

Closed ashishsme14 closed 3 years ago

ashishsme14 commented 3 years ago

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**

Swift Ques 1

BradLarson commented 3 years ago

While that's an interesting challenge, this seems like a more general Swift question and is not an issue involving the specific elements of Swift for TensorFlow. You might find similar questions on Stack Overflow (this one, for example) or on the Swift forums, and you would probably be better served by searching on those sites first.