查找循环链表中是否存在循环,并找到循环的节点

来源:互联网 发布:日久军警装备淘宝店 编辑:程序博客网 时间:2024/04/29 22:24
typedef struct _node{int data;struct _node *next;}node,*pnode;int FindLoop(node *head){node *p = NULL;node *q = NULL;if (head == NULL)return 0;p = head;q = head->next;//q==NULL(一个元素) //q->next==NULL(两个元素)//当链表中有循环,会发生p == q情况while (p!=NULL &&q!=NULL&&q->next!=NULL&&p!=q) {p = p->next;//p每次走一步q = q->next->next;//q每次走两步}if (p==q)return 1;elsereturn 0;}//node *FindLoop(node *head)//{//node *pc = head;//node *pf = NULL;//if (!pc)//return NULL;//while (pc)//{//pf = head;//while(pf && pf != pc)//{////当前结点的下一个结点是它前面的某个结点或者是它自己,则为循环处//if (pc->next == pf || pc->next == pc)//return pc->next;//pf = pf->next;//}//pc = pc->next;//}//return NULL;//}node * find_list_middle_node(node * list){if(list == NULL || list->next == NULL){return list;}node *p1 = list;node *p2 = list;while(p1&&p2&&p2->next){p1=p1->next;p2=p2->next->next;}if(p2->next==NULL || p2==NULL)return p1;}

0 0
原创粉丝点击