LeetCode-141:Linked List Cycle

来源:互联网 发布:手机淘宝咋退货退款 编辑:程序博客网 时间:2024/06/07 15:15

原题描述如下:

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

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

题意给定一个链表,判断该链表中是否出现了环。

解题思路:设定两个指针分别指向头结点,每次让第一个指针走一步,第二个指针走两步,若最终两个指针再次相遇,则说明存在环。

Java代码:

/**
 * 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 first = head;
        ListNode second = head;
        
        while(second != null && second.next != null){
            first = first.next;
            second = second.next.next;
            
            if(first == second){
                return true;
            }
        }
        
        return false;
    }
}
0 0
原创粉丝点击