Thursday, February 4, 2016

Middle of Linked List

Middle of Linked List

Find the middle node of a linked list.

Example
Given 1->2->3, return the node with value 2.

Given 1->2, return the node with value 1.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
 * Definition for ListNode
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param head: the head of linked list.
     * @return: a middle node of the linked list
     */
    public ListNode middleNode(ListNode head) { 
        // Write your code here
        ListNode p1 = head;
        ListNode p2 = head;
        
        if (head == null) {
            return null;
        }
        
        while(p1.next != null && p1.next.next != null) {
            p1 = p1.next;
            p1 = p1.next;
            p2 = p2.next;
        }
        
        return p2;
    }
}