https://blog.youkuaiyun.com/ccccc1997/article/details/81413403
题目
给定一个带有头结点 head 的非空单链表,返回链表的中间结点。
如果有两个中间结点,则返回第二个中间结点。

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
//[1,2,3,4,5]
//[1,2,3,4,5,6]
//两个指针,一个快指针,一个慢指针,快指针走两步,慢指针走一步,快指针走到尾部,慢指针到达中间
class Solution {
public ListNode middleNode(ListNode head) {
if(head==null || head.next==null)
return head;
ListNode slow=head;
ListNode fast=head;
while(fast!=null && fast.next!=null){
fast=fast.next.next;
slow=slow.next;
}
return slow;
}
}
本文介绍了一种使用快慢指针的方法来找到非空单链表的中间节点。如果存在两个中间节点,则返回第二个中间节点。该方法通过一个指针每次移动一步而另一个指针每次移动两步来实现。
234

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



