力扣链表面试题:
描述:
给定一个带有头结点 head 的非空单链表,返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。
解题思路:
使用快慢指针的办法,快指针一次跳两个结点,慢指针跳一个结点。则快指针走完全程刚好慢指针走一半。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode middleNode(ListNode head) {
if(head == null | head.next == null){
return head;
}
ListNode low = head;
ListNode fast = head.next;
while(fast != null && fast.next != null){
low = low.next;
fast = fast.next.next;
}
//若整个链表结点数为偶数,则按要求中间是low.next;若为奇数,则中间是low
if(fast == null){
return low;
}else{
return low.next;
}
}
}