4.
找出链表环的入口
- 第一步利用快慢指针判断是否为环 如果为环,则返回快慢指针的相遇点
- 将快指针移到链表头,然后两个指针每步移动一次,再次相遇时的结点为链表环的入口
#include<stdio.h>
#include<iostream>
#include<stdlib.h>
typedef struct node{
struct node * next;
int data;
}ElemSN;
//创建环型链表
ElemSN * createCirList(int *a,int n,int begin){
ElemSN * head,* t,* p;
int i;
head=t=NULL;
for(i=0;i<n;i++){
p=(ElemSN *)malloc(sizeof(ElemSN));
p->next=NULL;
p->data=a[i];
if(head==NULL){
t=head=p;
}else{
t=t->next=p;
}
}
p=NULL;
if(begin>0){
for(i=1,p=head;i<begin;i++){
p=p->next;
}
}
t->next=p;
return head;
}
//快慢指针
ElemSN * slowAndFast(ElemSN * head){
ElemSN *slow,*fast;
if(head==NULL){
return NULL;
}
slow=fast=head;
//快慢指针
while((fast!=NULL)&&(fast->next)!=NULL){
slow=slow-