找链表的中点。
样例
链表 1->2->3 的中点是 2。
链表 1->2 的中点是 1。
挑战
如果链表是一个数据流,你可以不重新遍历链表的情况下得到中点么?
解题思路:
快慢指针。
/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param head: the head of linked list.
* @return: a middle node of the linked list
*/
public ListNode middleNode(ListNode head) {
// write your code here
if(head == null)
return null;
ListNode slow = head;
ListNode fast = head;
while(fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
}
本文介绍了一种高效的链表中点查找算法,利用快慢指针技术,在单次遍历下找到链表的中间节点,适用于数据流场景,无需重新遍历。示例包括链表1->2->3的中点为2,链表1->2的中点为1。
2848

被折叠的 条评论
为什么被折叠?



