判断单链表中环的长度等问题

来源:互联网 发布:零基础学php要多久 编辑:程序博客网 时间:2024/06/14 23:55

给定一个单链表,只给出头指针h:

1、判断是否存在环

选定两个指针p1,p2,初始时p1=p2=h,循环执行以下操作p1=p1+1,p2=p2+2,判断p1==p2,若p1==p2,记交点为p,则存在环,否则不存在。(追赶问题)

2、求取环的长度

从p开始执行以下操作p1=p1+1,p2=p2+2,再次相交时,执行的操作数,即为环的长度。(追赶问题)

3、找出环的连接点

p点到交点的距离=h到交点的距离。

证明:


证毕

4、带环链表的长度

s+s1

 

code---根据上图构建链表

#include <stdio.h>#include <stdlib.h>typedef struct chain{int num;struct chain* next;}CH,NODE;NODE* newnode(void){NODE* temp;temp=(NODE*)malloc(sizeof(NODE));return temp;}NODE* createchain(void){int i;NODE* temp,*save=NULL,*h,*p;for(i=1;i<=7;i++){temp=newnode();temp->num=i;if(save==NULL){save=temp;h=save;}else{save->next=temp;save=temp;}if(i==4){p=save;}}save->next=p;return h;}void checkloop(NODE* h){int len1=0,len2=0;NODE* p1,*p2;p1=p2=h;p1=p1->next;p2=p2->next->next;while(p1!=p2){p1=p1->next;p2=p2->next->next;}len1=1;p1=p1->next;p2=p2->next->next;while(p1!=p2){p1=p1->next;p2=p2->next->next;len1++;}printf("The length of the loop is: %d\n",len1);p1=h;while(p1!=p2){len2++;p1=p1->next;p2=p2->next;}printf("The intersect node is: %d\n",p1->num);printf("The length of the chain is: %d\n",len1+len2);}int main(void){CH* h;h=createchain();checkloop(h);system("pause");return 0;}



0 0
原创粉丝点击