思路:快慢指针,快指针是慢指针的两倍
分析: 两个人赛跑,如果A速度是B的2倍,那么,当A到达终点的时候,B刚好到中间位置(这种思想很重要)
class Node{
int val;Node next;
public Node(int val){
this.val = val;
}
}
public class List {
public static void addNode(Node head,Node node){
Node p = head;
while(p.next != null){
p = p.next;
}
p.next = node;
}
public static int searchNode(Node head){
Node search = head.next;
Node mid = head.next;
while(search.next != null){
if(search.next.next != null){
search = search.next.next;
mid = mid.next;
}else{
search = search.next;
}
}
return mid.val;
}
public static void main(String[] args) {
Node head = new Node(0);
addNode(head,new Node(1));
addNode(head,new Node(2));
addNode(head,new Node(3));
addNode(head,new Node(4));
addNode(head,new Node(5));
int searchNode = searchNode(head);
System.out.println(searchNode);
}