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.
给定一个单链表,返回链表的中间节点,如果链表总数是奇数个,返回中间节点,如果链表总数是偶数个,则返回两个中间节点后一个。
关键技巧:快慢指针
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
//如果是奇数个,返回中间节点;如果是偶数个,返回两个中间节点的后一个
public ListNode middleNode(ListNode head) {
ListNode quick = head;
ListNode slow = head;
while (quick.next != null && quick.next.next != null){
quick = quick.next.next;
slow = slow.next;
}
//奇数
if (quick.next == null){
return slow;
} else {
return slow.next;
}
}
}