链表之带环的链表

链表之带环的链表

1.首先判断是否是带环的链表
2.找到环点

判断是否带环

传入一个Node指针,判断它指向的链表是否有环,有环返回1,无环返回0

int is_list_has_circle(Node *ptr){

	if(ptr==NULL)
		return NULL;
	Node * fast= ptr;
	Node * slow=ptr;

	while(fast!=NULL){
		
		if(fast->next!=NULL){
			fast=fast->next->next;
		}else{
			return 0;
		}
		slow=slow->next;

		if(slow==fast){
			return 1;
		}
		
	}

	return 0;
}

找到环点

Node* find_circle_node(Node *ptr){

	if(ptr==NULL)
		return NULL;
	Node * fast= ptr;
	Node * slow=ptr;

	Node * head=ptr;

	while(fast!=NULL){
		
		if(fast->next!=NULL){
			fast=fast->next->next;
		}else{
			return NULL;
		}
		slow=slow->next;

		if(slow==fast){
			slow=head;
			while(fast!=NULL){

				fast=fast->next;
				slow=slow->next;

				if(fast==slow){

					return slow;
				}
			}
		}
	}

	return NULL;


}

posted @ 2014-10-30 13:25  CommonQ  阅读(489)  评论(0编辑  收藏  举报