leetcode 142:环形链表Ⅱ

题目:环形链表Ⅱ

  • 题目描述:
    给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
    说明:不允许修改给定的链表。
    进阶:
    你是否可以不用额外空间解决此题?

解法一:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        std::set<ListNode *> node_set; //设置node_set
        while(head){  //遍历链表
            if(node_set.find(head)!=node_set.end()){    //如果node_set已经出现了
                return head;   //返回环的第一个节点
            }
            node_set.insert(head);   //将节点插入node_set
            head = head->next;
        }
        return NULL;//没有遇到环,则返回NULL
    }
};

解法二:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        ListNode *fast = head;  //快慢指针
        ListNode *slow = head;  
        ListNode *meet = NULL;  //相遇的节点
        while(fast){
            slow = slow->next;
            fast = fast->next;
            if(!fast){
                return NULL;   //如果fast遇到链表尾,则返回NULL
            }
            fast = fast->next;  //fast再走1步
            if(fast == slow){
                meet = fast;   //fast与slow相遇,记录相遇位置
                break;
            }
        }
        if(meet == NULL){
            return NULL;   //如果没有相遇,则证明无环
        }
        while(head&&meet){
            if(head == meet){  //当head与meet相遇,说明遇到环的起始位置
                return head;
            }
            head = head->next;  //head与meet每次走1步
            meet = meet->next;
        }
        return NULL;
    }
};

猜你喜欢

转载自blog.csdn.net/gjpzl/article/details/80151301
今日推荐