Note that there are some explanatory texts on larger screens.

plurals
  1. PORegarding finding the middle element of linked list
    primarykey
    data
    text
    <p>I am following the below approach to calculate the middle element from the <code>linked list</code> , but I want is there any built in method or any other approach which can also find the same easily , the approach that I am following is shown bellow..</p> <pre><code>import test.LinkedList.Node; 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; } } } </code></pre> <h2>Output:-</h2> <pre><code>length of LinkedList: 4 middle element of LinkedList : 2 </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload