careercup2.5

Given a circular linked list, implement an algorithm which returns node at the begin-
ning 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


可以用龟兔原则解这个题。即快指针每次走两格,慢指针每次走一格,那么在慢指针遍历一次之前会相遇。相遇以后,快指针回原地点,每次一格,慢指针每次一格,在此相遇即为环点。

具体证明有http://www.1point3acres.com/bbs/viewthread.php?tid=18162


#include <iostream>
using namespace std;
class Node{
public:
	int data;
    Node* next;
	Node(){this->next = 0;}
	Node(int a):data(a),next(0){}
};

class LinkList{
public:
	Node* head;
	Node* tail;

	LinkList(){ 
	   head = new Node(-1); 
	   tail = head;
	}
	LinkList(int ar[],int len){
		head = new Node(-1);
		tail = head;
		for(int i = 0; i<len; i++){
			tail->next = new Node(ar[i]);
		    tail = tail->next;
	    }
	}

	void insertion(int);
	Node* del(int i);
	void print()const{
		Node* p = head->next;
		 while(p)
		{
		  cout<<p->data<<" ";
		  p = p->next;
		  }
	}
};

void LinkList::insertion(int k){
	tail->next = new Node(k);
	tail = tail->next;
}

Node* LinkList::del(int i){
	Node* p = head->next;
	Node* k = head;
	while(p->data != i){
		k = p;
		p = p->next;
	}
	k->next = p->next;
	delete(p);
	return p->next;
}

int runn(LinkList l){
	Node* slow_p = l.head->next;
	Node* fast_p = l.head->next->next;

	while(slow_p != fast_p){
		slow_p = slow_p->next;
		fast_p = fast_p->next->next;
	}

	fast_p = l.head;
	while(slow_p != fast_p){
		slow_p = slow_p->next;
		fast_p = fast_p->next;
	}

	return slow_p->data;

}

int main(){
	int ar[]={1,3,5,67,8,9,45,78,777,33,12,11,76,4,43,7};
	LinkList ll(ar,16);
	Node* p = ll.head;
	for(int i = 1; i<=7; i++)
		p = p->next;
	ll.tail->next = p;
	cout<<runn(ll)<<endl;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值