876. 链表的中间结点

 

 

利用快慢指针来处理

时间O(n),空间O(1)

 1     public ListNode middleNode(ListNode head) {
 2         if(head==null || head.next==null) return head;
 3         ListNode slow=head,fast=head.next;
 4         while(fast!=null && fast.next!=null){
 5             slow=slow.next;
 6             fast=fast.next.next;
 7         }
 8         // 针对偶数个节点的特殊处理
 9         if(fast!=null){
10             slow=slow.next;
11         }
12         return slow;
13     }

 

posted @ 2021-05-06 09:09  jchen104  阅读(21)  评论(0)    收藏  举报