力扣:876. 链表的中间结点

This commit is contained in:
huangge1199 2021-02-07 13:46:11 +08:00
parent 7055d02388
commit 31ba7d7121
2 changed files with 52 additions and 0 deletions

View File

@ -0,0 +1,30 @@
package com.code.leet.Official.t20210207;
import com.code.leet.entiy.ListNode;
import java.util.ArrayList;
import java.util.List;
/**
* 给定一个头结点为 head 的非空单链表返回链表的中间结点
* <p>
* 如果有两个中间结点则返回第二个中间结点
*/
public class MiddleNode {
/**
* 我们可以继续优化方法二用两个指针 slow fast 一起遍历链表slow 一次走一步fast 一次走两步那么当 fast 到达链表的末尾时slow 必然位于中间
*
* 作者LeetCode-Solution
* 链接https://leetcode-cn.com/problems/middle-of-the-linked-list/solution/lian-biao-de-zhong-jian-jie-dian-by-leetcode-solut/
* 来源力扣LeetCode
* 著作权归作者所有商业转载请联系作者获得授权非商业转载请注明出处
*/
public ListNode middleNode(ListNode head) {
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
}

View File

@ -0,0 +1,22 @@
package com.code.leet.study.t20210207;
import com.code.leet.entiy.ListNode;
import java.util.ArrayList;
import java.util.List;
/**
* 给定一个头结点为 head 的非空单链表返回链表的中间结点
* <p>
* 如果有两个中间结点则返回第二个中间结点
*/
public class MiddleNode {
public ListNode middleNode(ListNode head) {
List<ListNode> list = new ArrayList<>();
while (head != null) {
list.add(head);
head = head.next;
}
return list.get(list.size() / 2);
}
}