码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode OJ 142. Linked List Cycle II

时间:2016-11-13 14:19:03      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:list   which   tmp   blog   nod   begin   内存   cycle   ret   

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;
    }
}

 

LeetCode OJ 142. Linked List Cycle II

标签:list   which   tmp   blog   nod   begin   内存   cycle   ret   

原文地址:http://www.cnblogs.com/YuNanlong/p/6052789.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!