首页 > 其他 > 详细

LeetCode——Linked List Cycle

时间:2015-09-28 18:41:30      阅读:229      评论:0      收藏:0      [点我收藏+]

Description:

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

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

在不借助辅助空间的情况下判断一个链表是否存在回路。

可以用两个指针,一个从头节点开始,一个从头节点的next节点开始,node1一次走一步,node2一次走两步,这样一来如果链表存在回路的话,这两个节点就会相遇。否则则不存在回路。

/**
 * 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 node1 = head, node2 = head.next;
        
        while(node1 != null && node2 != null && node2.next != null) {
            if(node1 == node2) {
                return true;
            }
            node1 = node1.next;
            node2 = node2.next.next;
        }
        
        return false;
        
    }
}

 

LeetCode——Linked List Cycle

原文:http://www.cnblogs.com/wxisme/p/4844538.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!