Middle of Linked List
Question:
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.
Code:
/**
* 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
// 好好审题
// 想好初始化
int length = 0;
ListNode cur = head;
while (cur != null) {
length++;
cur = cur.next;
}
int middle = (length + 1) / 2;
cur = head;
// return the pointing node,
// middle = index + 1
// so using (middle - 1 > 0)
while (middle - 1 > 0) {
cur = cur.next;
// 必杀!while loop里面的循环条件变化
middle--;
}
return cur;
}
}