Q2 Middle Of A Linked List
Thu Jan 05 2023 19:44:08 GMT+0000 (Coordinated Universal Time)
Saved by
@Ayush_dabas07
//{ Driver Code Starts
import java.util.*;
import java.io.*;
class Node{
int data;
Node next;
Node(int x){
data = x;
next = null;
}
}
class GFG{
static void printList(Node node)
{
while (node != null)
{
System.out.print(node.data + " ");
node = node.next;
}
System.out.println();
}
public static void main(String args[]) throws IOException {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t > 0){
int n = sc.nextInt();
Node head = new Node(sc.nextInt());
Node tail = head;
for(int i=0; i<n-1; i++)
{
tail.next = new Node(sc.nextInt());
tail = tail.next;
}
Solution g = new Solution();
int ans = g.getMiddle(head);
System.out.println(ans);
//printList(head);
t--;
}
}
}
// } Driver Code Ends
/* Node of a linked list
class Node {
int data;
Node next;
Node(int d) { data = d; next = null; }
}
*/
class Solution
{
int getMiddle(Node head)
{
if(head == null || head.next == null)
return head.data;
Node fast = head;
Node slow = head;
//2nd condition to stop at first mid of an even linked list
while(fast.next != null && fast.next.next != null ){
slow = slow.next;
fast = fast.next.next;
}
return slow.data;
}
}
content_copyCOPY
https://www.pepcoding.com/resources/data-structures-and-algorithms-in-java-levelup/linked-list/middle-of-a-linked-list/ojquestion
Comments