Answer the question
In order to leave comments, you need to log in
Singly linked list swift why error?
Plz explain why after {55, 5.99} nil is displayed and not a link to the next object
class Link {
private let iData: Int
private let dData: Double
public var next: Link!
public init(iData: Int, dData: Double) {
self.iData = iData
self.dData = dData
}
public func displayLink() {
print("{\(iData), \(dData)}")
}
}
class LinkList {
private var first: Link!
public func isEmpty() -> Bool {
return first == nil
}
// INSERT
public func insertFirst(iData: Int, dData: Double) {
let newLink = Link(iData: iData, dData: dData)
newLink.next = first
first = newLink
}
// DELETE
public func deleteFirst() -> Link? {
if var first = first {
let temp = first
first = first.next
return temp
}
return nil
}
//Display
public func displayList() {
print("List (first --> last)")
if let first = first {
var current = first
while current != nil {
current.displayLink()
current = current.next
print(current.next) // Error {55, 5.99} nil
}
}
print("----------")
}
}
let theList = LinkList()
theList.insertFirst(iData: 22, dData: 2.99)
theList.insertFirst(iData: 55, dData: 5.99)
theList.insertFirst(iData: 77, dData: 7.99)
theList.displayList()
Answer the question
In order to leave comments, you need to log in
1) .next does not always have to be ,
for example, for an element (iData: 22, dData: 2.99)
you don't have .next, but the class says that it always exists.
It follows that .next is an optional type
2) Same with .first in the list, it may or may not be. Suddenly you deleted everything and then it will crash.
3) The error just occurred due to the fact that I tried to take .next, which is not present
Below, I corrected the code with comments.
class Link {
private let iData: Int
private let dData: Double
public var next: Link?
public init(iData: Int, dData: Double) {
self.iData = iData
self.dData = dData
}
public func displayLink() {
print("{\(iData), \(dData)}")
}
}
class LinkList {
private var first: Link?
public func isEmpty() -> Bool {
return first == nil
}
// INSERT
public func insertFirst(iData: Int, dData: Double) {
let newLink = Link(iData: iData, dData: dData)
newLink.next = first
first = newLink
}
// DELETE
public func deleteFirst() -> Link? {
// Проверяем есть ли первый элемент, иначе удалить ничего нельзя и мы возращаем nil
guard let first = first else { return nil }
// Если есть первый элемент, то ему присваиваем значение второго
// Если второго нет, то ему присвоится значение nil
// А это значит мы удалили все элементы в списке
self.first = first.next
return self.first
}
//Display
public func displayList() {
print("List (first --> last)")
// Создаем стартовый элемент, который изначально равен первому
// Это опциональный тип и может быть nil, так как первый элемент тоже может быть nil
// Если вдруг мы все удалили
var element = first
// Потом сразу делаем проверку на nil
// Если элемента нет, то и выводить ничего не будем
while element != nil {
element?.displayLink()
element = element?.next
}
print("----------")
}
}
let theList = LinkList()
theList.insertFirst(iData: 22, dData: 2.99)
theList.insertFirst(iData: 55, dData: 5.99)
theList.insertFirst(iData: 77, dData: 7.99)
//theList.deleteFirst()
//theList.deleteFirst()
//theList.deleteFirst()
theList.displayList()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question