To find the median of all nodes in a linked list, we can follow below steps:
Here's the Swift code to implement the above steps:
main.swift551 chars28 lines
Here, we traverse the linked list using two pointers - a slow pointer and a fast pointer. The fast pointer moves twice as fast as the slow pointer. When the fast pointer reaches the end of the linked list, the slow pointer would have reached the middle of the list. We keep count of the number of nodes traversed to determine if the list has an odd or even length.
Finally, we return the median as a Double
value.
gistlibby LogSnag