给定一个头结点为 head
的非空单链表,返回链表的中间结点。
如果有两个中间结点,则返回第二个中间结点。
链接: https://leetcode-cn.com/problems/middle-of-the-linked-list/
目录
解题思路
普通解法
循环链表 统计出链表的长度sum。然后除2,然后再遍历一次找到链表对应节点返回就可以了。
代码
public static ListNode middleNode(ListNode head) {
ListNode temp = head;
int sum = 0;
while (temp != null) {
sum++;
temp = temp.next;
}
int mid = sum / 2;
for (int i = 0; i < mid; i++) {
if (head != null) {
head = head.next;
}
}
return head;
}
快慢指针
相比较普通解法只循环一次。慢指针走一步,快指针走两步,快指正走到尽头(也就是null),返回慢指针所在节点,刚好是链表的中间节点。哈哈哈
代码
public static ListNode middleNode(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode slowNode = head;
ListNode fastNode = head;
while(fastNode!=null && fastNode.next!=null) {
slowNode = slowNode.next;
fastNode = fastNode.next.next;
}
return slowNode;
}