1
+ ##==================================
2
+ ## Leetcode
3
+ ## Student: Vandit Jyotindra Gajjar
4
+ ## Year: 2020
5
+ ## Problem: 876
6
+ ## Problem Name: Middle of the Linked List
7
+ ##===================================
8
+ #
9
+ #Given a non-empty, singly linked list with head node head, return a middle node of linked list.
10
+ #
11
+ #If there are two middle nodes, return the second middle node.
12
+ #
13
+ #Example 1:
14
+ #
15
+ #Input: [1,2,3,4,5]
16
+ #Output: Node 3 from this list (Serialization: [3,4,5])
17
+ #The returned node has value 3. (The judge's serialization of this node is [3,4,5]).
18
+ #Note that we returned a ListNode object ans, such that:
19
+ #ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL.
20
+ #
21
+ #Example 2:
22
+ #
23
+ #Input: [1,2,3,4,5,6]
24
+ #Output: Node 4 from this list (Serialization: [4,5,6])
25
+ #Since the list has two middle nodes with values 3 and 4, we return the second one.
26
+ class Solution :
27
+ def middleNode (self , head ):
28
+ tmp = head #Referencing head value to tmp
29
+ counter = 0 #Initialize counter
30
+ while tmp : #While our head is not empty
31
+ counter += 1 #We'll traverse through list and increase our counter by 1.
32
+ tmp = tmp .next #We'll point to next value
33
+ middle = counter // 2 #Find the middle index of linked list, that return integer value
34
+ newTmp = head #Referencing head value to newTmp
35
+ for i in range (middle ): #Loop throuh middle in list
36
+ newTmp = newTmp .next #We'll point till we reach middle index
37
+ return newTmp #We'll return the newTmp value or serialization.
38
+ #Example:
39
+ #tmp = [1, 2, 3, 4, 5, 6]
40
+ #counter = 0
41
+ #While Loop
42
+ #tmp = [1, 2, 3, 4, 5, 6]
43
+ #counter = 1
44
+ #tmp = [2, 3, 4, 5, 6]
45
+ #counter = 2
46
+ #tmp = [3, 4, 5, 6]
47
+ #counter = 3
48
+ #tmp = [4, 5, 6]
49
+ #counter = 4
50
+ #tmp = [5, 6]
51
+ #counter = 5
52
+ #tmp = [6]
53
+ #counter = 6
54
+ #Loop terminates
55
+ #Middle = counter // 2 ===>>> 3
56
+ #newTmp = [1, 2, 3, 4, 5, 6]
57
+ #For loop
58
+ #i = 0
59
+ #newTmp = [2, 3, 4, 5, 6]
60
+ #i = 1
61
+ #newTmp = [3, 4, 5, 6]
62
+ #i = 2
63
+ #newTmp = [4, 5, 6]
64
+ #This newTmp we'll return as we reached the middle.
0 commit comments