CareerCup 2.6

来源:互联网 发布:淘宝超级掌柜 编辑:程序博客网 时间:2024/04/29 16:05

2.6 Given a circular linked list, implement an algorithem which returns the node at the beginning of the loop.

struct ListNode {    int val;    ListNode *next;    ListNode(int x) : val(x), next(NULL) {}};
ListNode* findBeginning(ListNode *head) {    ListNode *fast = head;    ListNode *slow = head;        while (fast && fast->next) {        slow = slow->next;        fast = fast->next->next;        if (slow == fast) {            break;        }    }        if (fast == NULL || fast->next == NULL) {        return NULL;    }        slow = head;    while (slow != fast) {        slow = slow->next;        fast = fast->next;    }    return fast;}


原创粉丝点击