Middle of Linked List
Find the middle node of a linked list.
Example
Given 1->2->3
, return the node with value 2.
Given 1->2
, return the node with value 1.
分析
1 value 1
1->2 value1
1->2->3 value 2
1->2->3->4 value 2
1->2->3->4->5 value 3
...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | /** * 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 ListNode slow = head, fast = head; while (fast != null && fast.next != null && fast.next.next != null ) { slow = slow.next; fast = fast.next.next; } return slow; } } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步