利用快慢指针寻找链表中点

快慢指针的原理类似于时钟里的分针时针,在链表中,二者同时从head首节点出发,快指针一次走两步,慢指针一次走一步,当快指针走到终点时,慢指针所在位置即为链表的中点。

代码:

class ListNode{
  int val;
  ListNode next;
}

ListNode getMidNode(ListNode head){ ListNode slow
= head, fast = head; while(fast != null){ slow = slow.next; fast = fast.next; if(fast != null){ fast = fast.next; } } return slow; }

练习:Leetcode 148. 排序链表,链接:https://leetcode-cn.com/problems/sort-list/。

posted @ 2022-04-30 13:18  夜满星河  阅读(332)  评论(0)    收藏  举报