版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/majichen95/article/details/85318228
找链表的中点。
样例
链表 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;
}
}