有兩個做用this
1 查看鏈表中是否有環形get
代碼以下ast
public boolean isSquare(){class
if(head!=null&&size>0){鏈表
Node<T> fast=head;next
Node<T> slow=head;static
}di
while(fast.next!=null&&slow.next!=null){while
fast=fast.next.next;co
slow=slow.next;
if(fast==slow){
return true;}
}
}
return false;
}
2 (快速找到未知長度鏈表的中間節點)0判斷鏈表中間位置
class Node<T>{
private T data;
private Node next;
public Node(T data ,Node next){
this.data=data;
this.next=next;
}}
public class getMiddle{
public Node<T> middle(Node<T> data){
Node fast=data;
Node slow=data;
while(fast.next!=null){
if(fast.next.next!=null){
fast=fast.next.next;
slow=slow.next;}
else{
fast=fast.next;}
}}
return slow;
}
public static void main(String [] args){
Node<Integer > l=new Node<Integer>(0,null);
Node<Integer> data=l;
for(int i=0;i<20;i++){
p.next=new Node<>(i+1,null);
p=p.next;}
System.out.println(new getMiddle<Integer>().middle(l).data);