Power Buckle Simple 876. 链表的中间节点 - 问题解决
最编程
2024-09-29 17:25:28
...
法一:
class Solution {
public ListNode middleNode(ListNode head) {
ListNode cur = head;
int n = 0;
while (cur != null) {
n++;
cur = cur.next;
}
ListNode curr = head;
for (int i = 0; i < n / 2; i++) {
curr = curr.next;
}
return curr;
}
}
法二:快慢指针
class Solution {
public ListNode middleNode(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while(true){
if(fast == null || fast.next == null){
break;
}
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
}
上一篇: 电子简介
下一篇: 前端项目依赖包漏洞解决方案