
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find the middle node of a singly linked list in Python
Suppose we have a singly linked list node, we have to find the value of the middle node. And when there are two middle nodes, then we will return the second one. We have to try to solve this in single pass.
So, if the input is like [5,9,6,4,8,2,1,4,5,2], then the output will be 2.
To solve this, we will follow these steps−
p:= node
d:= 0, l:= 0
while node is not null, do
if d is not same as 2, then
node:= next of node
l := l + 1, d := d + 1
otherwise,
p:= next of p, d:= 0
return val of p when l is odd otherwise value of next of p
Let us see the following implementation to get better understanding
Example
class ListNode: def __init__(self, data, next = None): self.val = data self.next = next def make_list(elements): head = ListNode(elements[0]) for element in elements[1:]: ptr = head while ptr.next: ptr = ptr.next ptr.next = ListNode(element) return head class Solution: def solve(self, node): p=node d=0 l=0 while node: if d!=2: node=node.next l+=1 d+=1 else: p=p.next d=0 return p.val if l & 1 else p.next.val ob = Solution() head = make_list([5,9,6,4,8,2,1,4,5,2]) print(ob.solve(head))
Input
Input: [5,9,6,4,8,2,1,4,5,2]
Output
2
- Related Questions & Answers
- Find middle of singly linked list Recursively in C++
- Python Program to Print Middle most Node of a Linked List
- Python program to delete a node from the middle of the Circular Linked List
- Python program to delete a new node from the middle of the doubly linked list
- Python program to insert a new node at the middle of the Doubly Linked List
- Python program to insert a new node at the middle of the Circular Linked List
- C++ Program to Delete the First Node in a given Singly Linked List
- C Program to reverse each node value in Singly Linked List
- Find kth node from Middle towards Head of a Linked List in C++
- Find the Kth Node from the end in a given singly Linked List using C++
- Program to find the K-th last node of a linked list in Python
- Write a program in C++ to insert a Node at the beginning of the given Singly linked list
- C# program to find node in Linked List
- Golang Program to define a singly linked list.
- JavaScript: How to Find the Middle Element of a Linked List?
Advertisements