Advertisement
gelita

876. Return the Middle of the Linked List

Jan 2nd, 2020
351
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 0.72 KB | None | 0 0
  1. /**
  2.  * Definition for singly-linked list.
  3.  * public class ListNode {
  4.  *     int val;
  5.  *     ListNode next;
  6.  *     ListNode(int x) { val = x; }
  7.  * }
  8.  */
  9. class Solution {
  10.     public ListNode middleNode(ListNode head) {
  11.         ListNode iterator = new ListNode(0);
  12.         iterator.next = head;
  13.         int count = 0 ;
  14.         while(iterator.next != null){
  15.             iterator = iterator.next;
  16.             count++;
  17.         }
  18.         if(count == 1){
  19.             return iterator;
  20.         }
  21.         count = (count/2) -1;  
  22.         iterator = head; //reset to head and iterate to middle integer
  23.         for(int i = 0; i < count; i++){
  24.             iterator = iterator.next;
  25.         }
  26.      return iterator.next;
  27.     }
  28. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement