您的位置:首页 > 其它

Linked List Cycle

2015-09-09 21:46 225 查看

题目描述: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) {
/*Set<ListNode> set=new HashSet<ListNode>();
ListNode p=head;
while(p!=null){
if(set.contains(p)) return true;
else set.add(p);
p=p.next;
}
return false;*/
if(head==null) return false;
ListNode p=head,q=head;
while(p.next!=null){
if(p.next==head) return true;
q=p;
p=p.next;
q.next=head;
}
return false;
}
}原题题目:https://leetcode.com/problems/linked-list-cycle/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息