您的位置:首页 > 其它

VS2010 验证时出错。HRESULT = '8000000A'

2013-03-04 11:40 323 查看
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?

CICT上有差不多的原题,

1. 初始化两个iterator都等于head, 设为a,b。
2. 每次迭代,a走一步,b走两步。
3. 如果a或者b走到null那就说明链表没有环,返回false,如果在某一步a==b则说明有环

/**
* 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) {
ListNode h1 = head;
ListNode h2 = head;

if(head == null){
return false;
}

while(true)
{
h1 = h1.next;
h2 = h2.next;
if( h1==null || h2 == null){
return false;
}else{
h2 = h2.next;
if(h2 == null){
return false;
}
}

if(h1 == h2){
return true;
}
}
}
}


本文出自 “在云端” 博客,请务必保留此出处http://kcy1860.blog.51cto.com/2488842/1318080
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: