find the mode of all nodes in a linked list in swift

To find the mode of a linked list, we need to count the occurrences of each node's value. We can achieve this by using a dictionary to store the frequencies of each value. Then, we can iterate through the dictionary to find the mode - the value(s) with the highest frequency.

Here's a function that takes in a linked list and returns the mode(s) of its nodes:

main.swift
func findMode(list: LinkedList<Int>) -> [Int] {

    var frequencies: [Int: Int] = [:] // dictionary to store frequencies
    var maxFrequency = 0

    // iterate through nodes and count frequencies
    for node in list {
        frequencies[node.value, default: 0] += 1
        maxFrequency = max(maxFrequency, frequencies[node.value]!)
    }

    // find mode(s) from frequencies dictionary
    var modes: [Int] = []
    for (value, frequency) in frequencies {
        if frequency == maxFrequency {
            modes.append(value)
        }
    }

    return modes
}
570 chars
22 lines

Here, we initialize a dictionary frequencies to store the frequencies of each value. We also initialize maxFrequency to keep track of the highest frequency seen so far.

We then iterate through each node in the linked list and update the corresponding frequency in frequencies. After iterating through all nodes, we have a dictionary containing the frequencies of each value.

Finally, we iterate through the frequencies dictionary and add all the values with the maximum frequency to an array modes. We then return modes, which contains the mode(s) of the linked list.

Note: this implementation assumes that there is at least one node in the linked list.

gistlibby LogSnag