查找列表是否含有環(一)——Leetcode系列(九)

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

My Answer:

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
        if(head == null){
            return false;
        }
        ListNode stepOne = head;
        ListNode stepTwo = head;
        while(true){
            if(stepTwo == null){
                return false;
            }
            stepTwo = stepTwo.next;
            if(stepTwo == null){
                return false;
            }
            stepTwo = stepTwo.next;
            stepOne = stepOne.next;
            if(stepTwo == stepOne){
                return true;
            }
        }
    }
}
題目來源:https://oj.leetcode.com/problems/linked-list-cycle/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章