1.题目
2.条件与思路
单链表只能从头开始遍历,不能随机访问
设置双指针one和two,同时从头结点开始遍历,one指针每次步长为1,two指针每次步长为2
当two指针首次指向空指针时,one指针所指节点即为链表中间节点
3.解题过程
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode middleNode(ListNode head) {
ListNode one = new ListNode();
ListNode two = new ListNode();
one = head;//步长为1的慢指针
two = head;//步长为2的快指针
while(two!=null){
if(two!=null){
two = two.next;
}else{
return one;
}
if(two!=null){
two = two.next;
}else{
return one;
}
one = one.next;
}
return one;
}
}
分析:
1.先执行两步走的快指针,后执行一步走的慢指针。
2.快指针每次向下移动时都要进行试探下一步是否为空指针,是则返回慢指针,不是才向下移动。
4.官方题解
class Solution {
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;
}
}