How to find middle element of LinkedList in Java in one pass
来源:互联网 发布:ae cc for mac 破解版 编辑:程序博客网 时间:2024/06/08 03:36
How do you find middle element of LinkedList in one pass is a programming question often asked to Java and non Java programmers in telephonicInterview. This question is similar tochecking palindrome or calculating factorial, where Interviewer some time also ask to write code. In order toanswer this questioncandidate 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 ofnext 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 tofind 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 programmingtutorial 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 withjava.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.
importtest.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 staticvoid 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 staticclass 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 staticvoid 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 staticclass 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
Read more: http://javarevisited.blogspot.com/2012/12/how-to-find-middle-element-of-linked-list-one-pass.html#ixzz2khW8pgKQ
- How to find middle element of LinkedList in Java in one pass
- Selenium - How to find the element in iframe
- How to pass arguments in exchange
- 1007. Find the middle element in a Linked List
- LinkedList---Delete Node in the Middle of Singly Linked List
- How to center absolute element in div?
- How to find number of a specific integer in an array of Fixnums ruby
- how to find shell type in linux
- How to find identifier in IOS7
- how to find error in log
- In Android how to display one view as overlay on top of another view?
- the diary of how to backup one more files in linux
- How to create different types of thread pool in Java
- In the middle of nowhere
- Pass in an array of Deferreds to $.when()
- How to find child controls that are located in the template of a parent control
- [Decrypting User Password]How to find password of a User in Oracle Apps R12?
- How to find second highest or maximum salary of Employee in SQL - Interview question
- org.apache.jasper.JasperException: java.lang.NullPointerException一个神奇的异常
- Javascript跳转问题总结
- Dynamic typing
- mac 常用软件
- syslog(),openlog(),closelog()
- How to find middle element of LinkedList in Java in one pass
- Redmine 安装
- HDU-1272 小希的迷宫(并查集判断输入的数据是否能成为一颗树)
- iOS -- 字典遍历排序
- Asp.net 自定义控件 => 抛出“未知的服务器标记” 异常 解决办法
- 优先队列的使用方法!
- Building a WebRTC Client for Android
- ORACLE的is null和=null的区别
- jbossCould not create deployment: file:/home/jboss-4.2.2/server/default/conf/jboss-service.xml