leetcode876.链表的中间节点

/**
* 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 slowNode = head;
ListNode fastNode = head;
while(true){
if(fastNode.next == null){
return slowNode;
}else if(fastNode.next != null && fastNode.next.next == null){
return slowNode.next;
}else{
slowNode = slowNode.next;
fastNode = fastNode.next.next;
}
}
}
}

浙公网安备 33010602011771号