您的位置:首页 > 其它

【LeetCode】Linked List Cycle

2013-10-29 22:21 411 查看
Given a linked list, determine if it has a cycle in it.

Follow up:

Can you solve it without using extra space?

java code : 很简单的判断单链表是否有环。

/**
* 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) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(head == null || head.next == null)
return false;
ListNode p = head, q = head.next;
while( q!= null && q.next != null)
{
if(p == q)
return true;
p = p.next;
q = q.next.next;
}
return false;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: