代码改变世界

141_Linked List Cycle

2016-03-21 16:33  FTD_W  阅读(132)  评论(0编辑  收藏  举报

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

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

 

判断一个单链表是否有环

解法一:记录下来遍历过的节点,但是当节点很多事会非常耗费时间,代码效率低

C#代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public bool HasCycle(ListNode head) {
        List<ListNode> nodeList = new List<ListNode>();
        while(head != null)
        {
            if(nodeList.Contains(head))
            {
                return false;
            }
            nodeList.Add(head);
            head = head.next;
        }
        return true;
    }
}

 

解法二:快慢指针,用两个指针,一个每次走一步,一个每次走两步,如果两个指针最终遇到,则说明是有环;如果遇到为NULL的指针则说明不存在环(因为是单链表)

C代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
bool hasCycle(struct ListNode *head) {
    struct ListNode * fast = head;
    struct ListNode * slow = head;
    while(fast != NULL && slow != NULL)
    {
        fast = fast->next;
        slow = slow->next;
        if(fast != NULL)
        {
            fast = fast->next;
        }
        else
        {
            return false;
        }
        
        if(fast == slow)
        {
            return true;
        }
    }
    return false;
    
}