LeetCode OJ 142. Linked List Cycle II

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Note: Do not modify the linked list.

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

 

Subscribe to see which companies asked this question

解答:

先用快慢指针判断是否有环,当然用快慢指针时注意避免对NULL指针解引用,然后如果有环的话从头节点开始遍历链表,每遍历一个节点就把环全部查找一遍,如果没找到就继续遍历下一个,当然这里要注意查找整个环时要标记一个终点,而那个终点在下面这个解法中是没有在内存循环中访问的,所以要注意这一点……

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode *detectCycle(struct ListNode *head) {
    struct ListNode *slow, *fast, *tmp;
    
    if(NULL == head)
        return NULL;
    else
        slow = head;
    if(NULL == slow->next)
        return NULL;
    else
        fast = slow->next;
    while(NULL != fast&&NULL != fast->next){
        if(fast == slow){
            break;
        }
        else{
            slow = slow->next;
            fast = fast->next->next;
        }
    }
    if(NULL == fast||NULL == fast->next){
        return NULL;
    }
    else{
        tmp = slow;
        while(head != tmp){
            slow = slow->next;
            while(slow != tmp){
                if(slow == head){
                    return head;
                }
                else{
                    slow = slow->next;
                }
            }
            head = head->next;
        }
        return head;
    }
}

 

转载于:https://www.cnblogs.com/YuNanlong/p/6052789.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值