Swift Link List Issue

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

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

Conditions / Instructions screen shot

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

I doubt that this forum is the right place for asking questions like this:
You can't expect someone else to do your homework — and if someone does, you won't learn.
Analyse the problem (order is reversed, isn't it?), and think what you can do about it (it's not that hard).

If you’re just starting out in programming, it can take some time to build your skills analyzing a problem.

I’d recommend first figuring out why the code is behaving the way it does.

You might consider working it out in a piece of paper.

Make a small diagram for the initial state and other small diagrams showing what happens after you call insert(data:) repeatedly.

When you first create a LinkedList, what’s the value of head?

When you call insert(data:) the first time, what happens? Go through line by line and figure out what the value of head is, if there are any nodes created, what the next node is. What happens when you call insert(data:) the next few times?

Once you understand why the code is doing things the way it does as written, it should help you figure out how to change the code to do what you want.

4 Likes

That's quite a bit more complicated that it needs to be, which is probably why you forgot to update count when position is 0.

Also, the code that you aren't allowed to change doesn't know about the at position: argument to insert, perhaps you don't need the position?

Here's a hint: what happens if you always insert at list.count?

You should step through this in the Xcode debugger. Knowing how to use the debugger to understand why code isn't behaving as you expect is a full-on super power.

1 Like

I know it was required by the instructor, but it's probably a bad idea to expose head, since you wouldn't want users to take that property and use it for unregulated link surgery.

As someone else on the thread mentioned, I don't want to give an answer to an assignment.

I do have two suggestions though.

The first is similar to my earlier suggestion.

Figuring out the answer to some questions will probably help lead you to a solution.

  1. What data value of the head node and its next node, and that node's next node, etc. would cause the results that you are currently getting?

  2. What data value would the head node and its next node, etc need to be get the results you want?

  3. Can you look at each line of code in your original insert(data:) method and see how it is building the nodes that leads to your current results, so they look like the answer to Question 1?

  4. How could you change your code so that the nodes end up looking like the answer to Question 2?

Second suggestion:
I am guessing that since you are using Node? that you have learned about Optionals in Swift. I'd suggest looking at the section on Optionals in the Swift Language Guide.
https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html

Which options have you tried, and (more importantly) what were your reasons for trying those? What result did you expect to see with those modifications, and what is your understanding of why the actual result isn’t what you expected?

I am confident that if you work through @James_Dempsey’s suggestions one by one, you will arrive at the answer. See if @Nobody1707’s hints help to guide you in the right direction. Alternatively, see if you can figure out how to step through your code with the debugger as has been suggested before, which is a great skill. These are all valuable skills that will help you tackle this and future problems.

The learning from this exercise comes from figuring out how to figure out the solution. The community is always happy to help if you get stuck, but you need to put in the effort of working through the problem and analyzing what you’re stuck on. We won’t give out answers to homework problems; it doesn’t help anyone.

6 Likes