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;
            } 
        }
    }
}
posted @ 2019-09-28 23:11  WillamZ  阅读(66)  评论(0)    收藏  举报