4.23 链表环操作
学学别人写一点总结也不错。睡了一个上午,下午还看了2场dota比赛,一天没学啥啊,明天要改变。
今天看了一下链表的东西,看到几个有用的东西。
1.如何判断链表是否有环。
It's easy to determine whether the link has a circle. Suppose there are two points P and Q. P and Q start from the head point. Every time Q move one step ,P move two steps. If circle exits, P and Q will meet.
bool hasLoop(node* head){ if(NULL==head) return true; node* p=head; node* q=head; while(p!=NULL&&p->next!=NULL){ p=p->next->next; q=q->next; if(p==q) return true; } return false; }
2.环的长度。
if you are sure the link has a circle, you can calculate the length. Assume point Q and P .Useing the method above ,P and Q will meet. When they meet first,allow Q move step by step . When p meet itself again,the steps is the circle length.
int looplen(node* head){ node *p=head; node *q=head; bool meet=false; int len=0; while(p&&p->next){ if(!meet){ p=p->next->next; q=q->next; if(p==q){ meet=true; } } else{ len++; q=q->next; if(q==p) break; } } return len; }
3.环的入口。
if you know the length of the circle is n . Assume Point P and Q again. Allow p move n steps fisrt. Then P and Q move step by step, when P meet Q , the p is the start point of the circle.
node* LoopEntrance(node* head){ node*p =head,*q=head; int len=circlelen(head); while(len--) p=p->next; while(p!=q){ p=p->next; q=q->next; } return p; }
浙公网安备 33010602011771号