【leetcode】Linked List Cycle

来源:互联网 发布:平刷王时时彩软件怎样 编辑:程序博客网 时间:2024/05/29 19:43

问题描述:

Given a linked list, determine if it has a cycle in it.Follow up:Can you solve it without using extra space? 


思路:

1.遍历链表,比较set中是否包含节点的地址,如果包含说明是有环,如果不包含,则将地址存入到set中;

缺点:leetcdoe显示time limited

//time limited..public boolean hasCycle1(ListNode head) {if(head==null)return false;Set<String> address = new HashSet<String>();while(head.next!=null){System.out.println(head.toString());if(address.contains(head.toString()))break;address.add(head.toString());head=head.next;}if(head.next==null)return false;        return true;    }

2.快慢指针:我很喜欢一个比喻,有两个人同时绕着操场跑,一个速度是另一个速度的两倍,这样以来两人肯定回碰到一起;快慢指针也是同理,在遍历时,让一个节点的后向遍历速度为next;另一个为next.next;如果有重复,两个指针肯定回碰到;

public boolean hasCycle(ListNode head) {boolean result = false;if(head==null)return false;ListNode flagA = head;ListNode flagB = head;while(flagB.next!=null&&flagB.next.next!=null){flagA=flagA.next;flagB=flagB.next.next;if(flagA==flagB){result = true;break;}}        return result;    }



0 0
原创粉丝点击