
附代码:
java
class Solution {
public ListNode middleNode(ListNode head) {
ListNode fast = head,slow = head;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
}
ACM模式:
java
import java.util.Scanner;
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
this.next = null;
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] nums = new int[n];
for(int i = 0;i < n;i++){
nums[i] = scanner.nextInt();
}
ListNode head = null;
if(n > 0){
head = new ListNode(nums[0]);
ListNode cur = head;
for(int i = 1;i < n;i++){
cur.next = new ListNode(nums[i]);
cur = cur.next;
}
}
Solution solution = new Solution();
ListNode mid = solution.middleNode(head);
System.out.println(mid.val);
scanner.close();
}
}
class Solution {
public ListNode middleNode(ListNode head) {
ListNode fast = head, slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
}