Group Group Group Group Group Group Group Group Group

Cahpter 07: Challenge 4: Merge two lists?

I copied mergeSorted() from the final code.
Only input values ​​were as follows.

code…

example(of: “Merge two lists”) {
var list1 = LinkedList()
list1.push(1)
list1.push(4)
list1.push(10)
list1.push(11)

var list2 = LinkedList<Int>()
list2.push(-1)
list2.push(2)
list2.push(3)
list2.push(6)

let mergedList = mergeSorted(list1, list2)
print("Merged list: \(mergedList)")

}

The output value is as follows.
Merged list: 6 -> 3 -> 2 -> -1 -> 11 -> 10 -> 4 -> 1

This is because the header values ​​of the list are left: 11 and right: 6.
There is a problem that it cannot be aligned normally.

What did I do wrong?

The input values ​​in the book
var list = LinkedList()
list.push(3)
list.push(2)
list.push(1)
var anotherList = LinkedList()
anotherList.push(-1)
anotherList.push(-2)
anotherList.push(-3)

I am doing this.
If it is not aligned, is it not considered?
Should it always be in the order of entering the largest value first, like a stack?

thank!

Hi @hyegon,

If my understanding is correct, then you are trying to pass above lists and then merge them by using the function provided in the solution.

If this is the case, then the issue is occurring due the lists, you are passing. For merge function(provided in the solution), you need to pass it sorted lists(i.e. ascending), only then you can merge them in the ascending order.
As you are pushing numbers in the list, then it is going to be added at the first position(i.e. head of list), due to which, your list is in descending order.