From 0c792afd87e88356a5bf1bf75debd7b0a0ab7d19 Mon Sep 17 00:00:00 2001 From: Yashika Gupta Date: Fri, 16 Oct 2020 18:01:56 +0530 Subject: [PATCH] Update_middle_element_of_linked_list Add More method for finding middle element in linked list , for the ease of learners --- .../middle_element_of_linked_list.py | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/data_structures/linked_list/middle_element_of_linked_list.py b/data_structures/linked_list/middle_element_of_linked_list.py index 185c4ccbbb0a..c93f5cd9b9af 100644 --- a/data_structures/linked_list/middle_element_of_linked_list.py +++ b/data_structures/linked_list/middle_element_of_linked_list.py @@ -1,3 +1,5 @@ + #METHOD:1 + class Node: def __init__(self, data: int) -> int: self.data = data @@ -62,3 +64,52 @@ def middle_element(self) -> int: data = int(input().strip()) link.push(data) print(link.middle_element()) + + + + #METHOD:2 + +# Python program to find the middle of a +# given linked list + +class Node: + def __init__(self, value): + self.data = value + self.next = None + +class LinkedList: + + def __init__(self): + self.head = None + + # create Node and and make linked list + def push(self, new_data): + new_node = Node(new_data) + new_node.next = self.head + self.head = new_node + + def printMiddle(self): + temp = self.head + count = 0 + + while self.head: + + # only update when count is odd + if (count & 1): + temp = temp.next + self.head = self.head.next + + # increment count in each iteration + count += 1 + + print(temp.data) + +# Driver code +llist = LinkedList() +llist.push(1) +llist.push(20) +llist.push(100) +llist.push(15) +llist.push(35) +llist.printMiddle() +