Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

How to efficiently find the middle node of a singly linked list without counting its nodes, in Java?

/*
	This is an implementation that shows how
	to efficiently get to the middle node 
	of a singly linked list whose size is not 
	known in advance.
	Each linked list node has an integer value
	as well as a next pointer that points to 
	the next node or null in case of tail of list.
	
	Let n be the number of nodes in the list.
	Time complexity: O(n) 
	Space complexity: O(1)
*/
public class MiddleNode {
	private ListNode head;
	public MiddleNode() {
		/*
		 * Create below linked list
		 * 0 -> 1 -> 2 -> 3 -> 4
		 */
		head = new ListNode(0, null);
		ListNode prev = head, temp;
		for (int i = 1; i <= 4; i++) {
			temp = new ListNode(i, null);
			prev.next = temp;
			prev = temp;
		}
	}
	public static void main(String[] args) {
		MiddleNode application = new MiddleNode();
		ListNode middleNode = application.findMiddleNode();
		System.out.println(middleNode.val); // 2
	}
	// Two pointers are maintained, namely fastPtr and slowPtr.
	// fastPtr advances by 2 steps every time
	// while the slow one by 1 step only.
	public ListNode findMiddleNode() {
		ListNode slowPtr = head, fastPtr = head;
		// By the time the fastPtr reaches the end of list
		// the slowPtr would reach the middle node
		while (fastPtr != null && fastPtr.next != null) {
			slowPtr = slowPtr.next;
			fastPtr = fastPtr.next.next;
		}
		return slowPtr;
	}
	// Class representing a linked list node
	// with pointers to value and next node
	private class ListNode {
		int val;
		ListNode next;
		ListNode(int val, ListNode next) {
			this.val = val;
			this.next = next;
		}
	}
}
Comment

PREVIOUS NEXT
Code Example
Java :: android action key 
Java :: android display drawable in imageview 
Java :: java swing stripes 
Java :: how to use base64.getdecoder() android 
Java :: java repeat loop cycle for 
Java :: difference between offer and add in linkedlist in java 
Java :: programmation android avoir acces à la liste des instants de partage 
Java :: java klasse 
Java :: the result o trim is ignored java 
Java :: Date from String java11 
Java :: add text to jlable 
Java :: how to clear activity stack in android 
Java :: java public static void main 
Java :: mapsid jpa 
Java :: javafx change text size 
Java :: java how to get current time 
Java :: use view binding in fragment 
Java :: input array through scanner in java 
Java :: get file extension java 
Java :: sum of all numbers in array java 
Java :: add certificate to java truststore 
Java :: list of BigInteger to list of long 
Java :: java regex ip 
Java :: convert optional object to object java 
Java :: calculate mean from arraylist jaca 
Java :: switch activity android studi 
Java :: get text from edittext android 
Java :: how to iterate hashmap java 
Java :: java version 
Java :: how to scan a string in java 
ADD CONTENT
Topic
Content
Source link
Name
7+4 =