find the median of all nodes in a linked list in python

To find the median of all nodes in a linked list in python, you can follow the steps given below:

  1. Traverse the linked list and store all the nodes' values in an array.
  2. Sort the array in ascending order.
  3. Calculate the length of the array.
  4. If the length of the array is odd, then the median will be the middle element.
  5. If the length of the array is even, then the median will be the average of the middle two elements.

Here's the code snippet to find the median of all nodes in a linked list:

main.py
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None

    def append(self, data):
        new_node = Node(data)

        if not self.head:
            self.head = new_node
            return

        current = self.head
        while current.next:
            current = current.next

        current.next = new_node

    def find_median(self):
        if not self.head:
            return None

        current = self.head
        values = []
        while current:
            values.append(current.data)
            current = current.next

        values.sort()
        n = len(values)
        if n % 2 == 0:
            median = (values[n//2-1] + values[n//2]) / 2
        else:
            median = values[n//2]

        return median
846 chars
41 lines

In this code snippet, we have defined two classes Node and LinkedList to represent a node and a linked list, respectively. We have also defined a method find_median in the LinkedList class that traverses the linked list and calculates the median of all nodes' values. Note that this method assumes that the node values are numeric.

gistlibby LogSnag