UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Swift Link List Reversal

Forums > Swift

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.

https://i.stack.imgur.com/cBSA7.jpg

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

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.