Skip to content

Instantly share code, notes, and snippets.

@ozkansari
Created April 12, 2020 14:46
Show Gist options
  • Save ozkansari/0f30827c883376285964403a4fc6c4a5 to your computer and use it in GitHub Desktop.
Save ozkansari/0f30827c883376285964403a4fc6c4a5 to your computer and use it in GitHub Desktop.
Middle of the Linked List : Given a non-empty, singly linked list with head node head, return a middle node of linked list. If there are two middle nodes, return the second middle node. https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/529/week-2/3290/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class LinkedListMiddleNode {
public ListNode solve(ListNode head) {
int size = 0;
// Go to the last node to find the size
ListNode current = head;
while(current != null) {
current = current.next;
size++;
}
int middle = size/2;
// Go to the middle node
current = head;
for(int i=0; i < middle; i++) {
current = current.next;
}
return current;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment