C++ 链表求环

已知链表中可能存在环,若有环返回环起始节点,否则返回NULL。

//方法一,使用set求环起始节点。

//遍历链表,将链表中节点对应的指针(地址)插入set。 在遍历时插入节点前,需

//要在set中查找,第一个在set中发现的的节点地址Axitrader代理申请http://www.kaifx.cn/broker/ax...,即是链表环的起点。

//Runtime: 24 ms,Memory Usage: 12 MB。

class Solution

{

public:

Solution(){}

~Solution(){}

ListNode* detectCycle(ListNode* head)

{

std::set node_set;

while (head)

{

if (node_set.find(head)!=node_set.end())

{

return head;

}

node_set.insert(head);

head = head->next;

}

return NULL;

}

};

/*

//方法二:快慢指针。Runtime: 12 ms,Memory Usage: 9.9 MB。

//时间复杂度为O(n)

class Solution

{

public:

Solution(){}

~Solution(){}

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 = fast->next;

if (fast==slow)

{

meet = fast;

break;

}

}

if (meet==NULL)

{

return NULL;

}

while (head&&meet)

{

if (head==meet)

{

return head;

}

head = head->next;

meet = meet->next;

}

return NULL;

}

};

*/

int main()

{

ListNode a(12);

ListNode b(34);

ListNode c(31);

ListNode d(41);

ListNode e(51);

ListNode f(61);

ListNode g(71);

a.next = &b;

b.next = &c;

c.next = &d;

d.next = &e;

e.next = &f;

f.next = &g;

g.next =&c;

Solution solve;

ListNode* node = solve.detectCycle(&a);

if (node)

{

printf("%d\n",node->val);

}

else

{

printf("NULL\n");

}

return 0;

}

你可能感兴趣的:(c++)