To find the mode (most frequent element) of all nodes in a linked list, we can use a map to keep track of the frequency of each element in the list. We can iterate through the list, incrementing the frequency of each element in the map. Finally, we can iterate through the map to find the element with the highest frequency.
Here's the Go code to find the mode of all nodes in a linked list:
main.go464 chars22 lines
We define a Node
struct to represent each node in the linked list, with an int
data field and a pointer to the next node.
The findMode
function takes a pointer to the head node of the linked list as its only argument, and returns the mode value as an int
.
Inside the function, we create an empty map freqMap
to keep track of the frequency of each element in the list, and initialize maxFreq
and mode
to 0.
We then iterate through the linked list using a for
loop, with a curr
pointer initialized to the head of the list. We increment the frequency of the current element curr.data
in the freqMap
using the syntax freqMap[curr.data]++
.
If the frequency of the current element is greater than maxFreq
, we update maxFreq
and mode
to the current element's value.
Finally, we return mode
, which is the value of the element with the highest frequency in the list.
gistlibby LogSnag