力扣 简单 876.链表的中间结点
题目介绍
题解
法一:
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;
}
}
原文地址:https://blog.csdn.net/qq_51352130/article/details/142551726
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!