CareerCup-2.5

Given a circular linked list, implement an algorithm which returns node at the beginning of the loop 
DEFINITION
Circular linked list: A (corrupt) linked list in which a node’s next pointer points to an 
earlier node, so as to make a loop in the linked list 
EXAMPLE
input: A -> B -> C -> D -> E -> C [the same C as earlier]
output: C

我写了第一个方法,时间复杂度是Ο(n^2),答案是第二个方法,想了会才明白,复杂度是Ο(n)

#include <iostream>
using namespace std;

// Creating a Linked List:
struct Node
{
    Node(int d):data(d){next = NULL;};
    int data;
    Node* next;
};

Node* findPar(Node* head)
{
    if(head == NULL) return NULL;
    Node *p, *q = head->next;
    int countq = 0, countp = 0;
    while(q != head && q != NULL)
    {
        countq ++;
        p = head;
        countp = 0;
        while(p != q)
        {
            countp ++;
            p = p->next;
        }
        if(countp != countq)
            return p;
        else
            q = q->next;
    }
    if(q == head)
        return head;
    else
        return NULL;
};

/* 设head距离环交点k,环长度为n。q以2倍p的速度前进。p到达环交点的时候
 * q已走出环交点k步,q向前n-k步是p。继续前进当他们相遇时,p又走出n-k步,
 * 距离环交点n-k。q回到head,与p以相同速度前进,q走到环交点的时候p距离
 * 环交点n,他们此时在交点相遇。 
 */ 
Node* findPar2(Node* head)
{
    Node *p = head;
    Node *q = head;
    while(p->next != NULL)
    {
        p = p->next;
        q = q->next->next;
        if(p == q)
        {
            break;
        }
    }
    if(q->next == NULL)
    {
        return NULL;
    }
    p = head;
    while(p != q)
    {
        p = p->next;
        q = q->next;
    }
    return q;
};

int main()
{
    Node* head = new Node(1);
    head->next = new Node(2);
    head->next->next = new Node(3);
    head->next->next->next = new Node(4);
    head->next->next->next->next = new Node(5);
    head->next->next->next->next->next = head->next->next;
    cout<<findPar(head)->data<<endl;
    cout<<findPar2(head)->data<<endl;
    system("pause"); 
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值