141. 链表是否成环 Linked List Cycle

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

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

题意:判断链表是否成环。

注意:最后一个节点的next指针,有可能指向链表中任意一个节点

方法一:使用HashSet,保存遍历过的节点的HashCode

  1. public class Solution {
  2. public bool HasCycle(ListNode head) {
  3. if (head == null) {
  4. return false;
  5. }
  6. ListNode node = head;
  7. HashSet<int> hashSet = new HashSet<int>();
  8. hashSet.Add(node.GetHashCode());
  9. while (node.next != null) {
  10. node = node.next;
  11. int hash = node.GetHashCode();
  12. if (hashSet.Contains(hash)) {
  13. return true;
  14. } else {
  15. hashSet.Add(hash);
  16. }
  17. }
  18. return false;
  19. }
  20. }
方法二:使用两个指针,一个快一个慢,如果两个指针相遇,则链表成环
  1. public class Solution {
  2. public bool HasCycle(ListNode head) {
  3. if (head == null || head.next == null) {
  4. return false;
  5. }
  6. ListNode slow = head;
  7. ListNode fast = head;
  8. while (fast.next != null && fast.next.next != null) {
  9. slow = slow.next;
  10. fast = fast.next.next;
  11. if (slow == fast) {
  12. return true;
  13. }
  14. }
  15. return false;
  16. }
  17. }





posted @ 2017-02-28 00:18  xiejunzhao  阅读(132)  评论(0)    收藏  举报