find the kth largest node in a linked list in swift

To find the kth largest node in a linked list in Swift, we can use a simple technique that involves sorting the list in descending order and then returning the kth node.

First, we need to define a Node class with a value and a next property to create the linked list:

main.swift
class Node<T> {
    let value: T
    var next: Node<T>?
    
    init(value: T, next: Node<T>? = nil) {
        self.value = value
        self.next = next
    }
}
164 chars
10 lines

Then we can define a function findKthLargest that takes a linked list and an integer k as inputs:

main.swift
func findKthLargest<T: Comparable>(_ head: Node<T>?, _ k: Int) -> T? {
    guard let head = head else { return nil }
    
    // Step 1: Sort the nodes in descending order
    var current = head
    var nodes = [current.value]
    while current.next != nil {
        current = current.next!
        nodes.append(current.value)
    }
    nodes.sort(by: >)
    
    // Step 2: Return the kth largest node if it exists
    if k <= 0 || k > nodes.count {
        return nil
    } else {
        return nodes[k-1]
    }
}
517 chars
20 lines

Here, we use an array nodes to store the values of all nodes in the linked list by traversing the list. Then we sort the array in descending order. Finally, we return the kth largest value from the array if it exists (i.e., if k is within the range of the array).

We can test the function with a sample linked list:

main.swift
let list = Node(value: 1, next: Node(value: 3, next: Node(value: 2, next: Node(value: 5))))
print(findKthLargest(list, 2)) // Output: 3
136 chars
3 lines

In this example, the linked list is 1 -> 3 -> 2 -> 5, and the 2nd largest node is 3. The function correctly returns 3 as the output.

gistlibby LogSnag