Linked List Cycle

来源:互联网 发布:淘宝卖家的需求分析 编辑:程序博客网 时间:2024/05/16 14:36

这道题目在考研的时候碰见过

public class Solution {public static void main(String[] args) {// TODO Auto-generated method stub}public boolean hasCycle(ListNode head) {if(head==null)return false;        ListNode node1 = head;//每次走一步        ListNode node2 = head;//每次走两步        while(node2.next!=null&&node2.next.next!=null)        {        node1 = node1.next;        node2 = node2.next.next;        if(node1==node2)//如果有环,node2肯定能跟node1碰见。        return true;        }        return false;    }}class ListNode {      int val;      ListNode next;      ListNode(int x) {          val = x;          next = null;      }  }




0 0