876. 链表的中间结点
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode middleNode(ListNode head) {
ListNode temp = head;
int count = 0;
while(temp != null) { //首先想到的暴力方法..
count ++;
temp = temp.next;
}
int n = count / 2 + 1;
temp = head;
for (int i = 1; i < n; i++) {
temp = temp.next;
}
return temp;
}
}
快慢指针法:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode middleNode(ListNode head) {
ListNode fast = head, slow = head;
while (fast != null && fast.next != null) { //别人的方法,两个轮子滚
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
}