How do you find middle element of LinkedList in one pass is a programming
question often asked to Java and non Java programmers in telephonic Interview.
This question is similar to checking
palindrome or calculating
factorial, where Interviewer some time also ask to write code. In order to answer this question candidate must be familiar with LinkedList data structure
i.e. In case of singly LinkedList, each node of Linked List contains data and
pointer, which is address of next Linked List and last element of Singly Linked
List points towards null. Since in order to find middle element of Linked List
you need to find length of LinkedList, which is counting elements till end i.e.
until you find the last element on Linked List. What makes this data structure
Interview question interesting is that you need to find middle element of LinkedList in one pass and you don’t know length
of LinkedList. This is where candidates logical ability puts into test, whether he is familiar with space and time
trade off or not etc. As if you think carefully you can solve this problem by
using two pointers as mentioned in my last post on How
to find length of Singly Linked List in Java. By using two pointers,
incrementing one at each iteration and other at every second iteration. When
first pointer will point at end of Linked List, second pointer will be pointing
at middle node of Linked List. In fact
this two pointer approach can solve multiple similar problems e.g. How to find
3rd element from last in a Linked List in one Iteration or How to
find nth element from last in a Linked List. In this Java programming tutorial
we will see a Java program which finds middle element of Linked List in one
Iteration.
Java program to find middle element of LinkedList in one pass
Here is complete Java program to find middle node of Linked List in Java.
Remember LinkedList class here is our custom class and don’t confuse this class
with java.util.LinkedList
which is a popular Collection class
in Java. In this Java program, our class LinkedList represent a linked list
data structure which contains collection of node and has head and tail. Each Node
contains data and address part. Main method of LinkedListTest class is used to
simulate the problem, where we created Linked List and added few elements on it
and then iterate over them to find middle element of Linked List in one pass in
Java.
import test.LinkedList.Node;
/**
* Java program to find middle element of linked list in one pass.
* In order to find middle element of linked list we need to find length first
* but since we can only traverse linked list one time, we will use two pointers
* one which we will increment on each iteration while other which will be
* incremented every second iteration. so when first pointer will point to the
* end of linked list, second will be pointing to the middle element of linked list
* @author
*/
public class LinkedListTest {
public static void main(String args[]) {
//creating LinkedList with 5 elements including head
LinkedList linkedList = new LinkedList();
LinkedList.Node head = linkedList.head();
linkedList.add( new LinkedList.Node("1"));
linkedList.add( new LinkedList.Node("2"));
linkedList.add( new LinkedList.Node("3"));
linkedList.add( new LinkedList.Node("4"));
//finding middle element of LinkedList in single pass
LinkedList.Node current = head;
int length = 0;
LinkedList.Node middle = head;
while(current.next() != null){
length++;
if(length%2 ==0){
middle = middle.next();
}
current = current.next();
}
if(length%2 == 1){
middle = middle.next();
}
System.out.println("length of LinkedList: " + length);
System.out.println("middle element of LinkedList : " + middle);
}
}
class LinkedList{
private Node head;
private Node tail;
public LinkedList(){
this.head = new Node("head");
tail = head;
}
public Node head(){
return head;
}
public void add(Node node){
tail.next = node;
tail = node;
}
public static class Node{
private Node next;
private String data;
public Node(String data){
this.data = data;
}
public String data() {
return data;
}
public void setData(String data) {
this.data = data;
}
public Node next() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public String toString(){
return this.data;
}
}
}
Output:
length of LinkedList: 4
middle element of LinkedList : 2
/**
* Java program to find middle element of linked list in one pass.
* In order to find middle element of linked list we need to find length first
* but since we can only traverse linked list one time, we will use two pointers
* one which we will increment on each iteration while other which will be
* incremented every second iteration. so when first pointer will point to the
* end of linked list, second will be pointing to the middle element of linked list
* @author
*/
public class LinkedListTest {
public static void main(String args[]) {
//creating LinkedList with 5 elements including head
LinkedList linkedList = new LinkedList();
LinkedList.Node head = linkedList.head();
linkedList.add( new LinkedList.Node("1"));
linkedList.add( new LinkedList.Node("2"));
linkedList.add( new LinkedList.Node("3"));
linkedList.add( new LinkedList.Node("4"));
//finding middle element of LinkedList in single pass
LinkedList.Node current = head;
int length = 0;
LinkedList.Node middle = head;
while(current.next() != null){
length++;
if(length%2 ==0){
middle = middle.next();
}
current = current.next();
}
if(length%2 == 1){
middle = middle.next();
}
System.out.println("length of LinkedList: " + length);
System.out.println("middle element of LinkedList : " + middle);
}
}
class LinkedList{
private Node head;
private Node tail;
public LinkedList(){
this.head = new Node("head");
tail = head;
}
public Node head(){
return head;
}
public void add(Node node){
tail.next = node;
tail = node;
}
public static class Node{
private Node next;
private String data;
public Node(String data){
this.data = data;
}
public String data() {
return data;
}
public void setData(String data) {
this.data = data;
}
public Node next() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public String toString(){
return this.data;
}
}
}
Output:
length of LinkedList: 4
middle element of LinkedList : 2
That’s all on How to find middle element of LinkedList in one pass.
As I said this is a good interview question to separate programmers from non
programmers. Also technique mentioned here to find middle node of LinkedList
can be used to find 3rd element from Last
or nth element from last in a LinkedList as well.
Other Java programming tutorials from Javarevisited blog
14 comments:
Maybe my mind is still not awaken after Christmas laziness, but... does this code really return middle element? I think it returns last element with even index. In this code it is solved like you were incrementing index every second time. If you update reference to current every second time, nothing good will come out of this. I'd set middle = middle.next() in loop and also ... initialize length as 0 (I don't consider head element as real element of the list (length should return number of elements carrying data). Greetings!
How would you pick a uniform random element in linked list with unknown length in one pass or if not two passes? http://dbmall27.blogspot.com/
@Pio Jac, you are right if we don't consider head as real element. In that case initialing length with 0 make sense. Also In order to handle odd length e.g. 3, 5 or 7 where middle element is not updated, we need to handle once loop finished. I have updated code. Thanks for pointing out, it seems, its me, who has Christmas laziness :)
Can you please write code for How to find 3rd element from last in Singular Linked List, I didn't get your point on saying that same technique can be used to find Nth element from last in singly linked list. Sorry.
I was asked to find middle item in a linked list in single pass and when I asked what is length of linked list they say, you need to find that as well. I didn't thought that I can use two pointers or two variables to keep track of middle and last item, something I missed. By the way What is big O for best case and worst case for this solution ?
In what aspect does this separate the programmers from nonprogrammers, even when you yourself didn't elaborate a complete algorithm?
What is a programmer and what is a nonprogrammer?
@Anonymous, aspect here is coding, converting logic to code. algorithm here is simple where one pointer is incremented on each iteration, while other is incremented in every second iteration. let me know which part you didn't understand.
Actually, I would dispute the assertion that this is being done "in one pass". You're making two separate passes through the list - it's just that you're doing them concurrently and not consecutively.
instead of checking length why not you just increment one pointer twice and other pointer only one. this would make your linked list middle element checking code simpler.
I have to agree with Ken, you just just do two traversals within one loop.
@Guido, Can you please elaborate? I think node.next() doesn't traverse the list it just like incrementing pointer, don't agree?
@Javin: I understand it just increments the pointer.
But as far as I can see, the code keeps track of two elements (i.e. pointers) in the loop: middle and current.
So even though it is executed within one for-loop, I do see two traversals:
* current looping all the way till the end
* middle looping till the middle
That is why I agreed with the statement of Ken that I would not call this one pass. Could just be a word thing and that with one-pass here it is meant you are only allowed to use one for-loop.
Ken and Guido.. Good Catch.. I had the same question when I read the article. As you said, if it is a wording issue(like using one for-loop), it clears my doubt.
- Durai
Hi,
The simple way to find the middle element is written below
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Set;
import javax.swing.text.html.HTMLDocument.Iterator;
import javax.xml.soap.Node;
public class test2 {
public static void main(String args[])
{
LinkedList l=new LinkedList();
l.add(2);
l.add(3);
l.add(9);
l.add(4);
java.util.Iterator i1=l.iterator();
java.util.Iterator i2=l.iterator();
int i=0;
int middle = 0;
while(i1.hasNext())
{
if(i==0)
{
i1.next();
i=1;
}
else if(i==1)
{
if(i1.hasNext())
{
i1.next();
middle=(Integer) i2.next();
i=0;
}
}
}
System.out.println("middle"+middle);
}
}
Post a Comment