Advertisement
CreateWithChirag

Middle Of Linked List

Feb 28th, 2023
828
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.64 KB | Source Code | 0 0
  1. /**
  2.  * Definition for singly-linked list.
  3.  * public class ListNode {
  4.  *     int val;
  5.  *     ListNode next;
  6.  *     ListNode() {}
  7.  *     ListNode(int val) { this.val = val; }
  8.  *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  9.  * }
  10.  */
  11. class Solution {
  12.     public ListNode middleNode(ListNode head) {
  13.        
  14.         if(head == null || head.next == null){
  15.             return head;
  16.         }
  17.  
  18.         ListNode slow = head;
  19.         ListNode fast = head;
  20.  
  21.         while(fast != null && fast.next != null){
  22.             slow = slow.next;
  23.             fast = fast.next.next;
  24.         }
  25.         return slow;
  26.  
  27.     }
  28. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement