单向链表是否成环

来源:互联网 发布:程序员考试通过条件 编辑:程序博客网 时间:2024/06/01 14:04

只需要:

两指针P1,P2均指向头结点,同时移动,P1每次后移1个节点,P2每次后移两个节点,当P1=P2时候则表示存在环的。

#include <stdio.h>#include <stdlib.h>typedef struct _A{int data;struct _A* next;}A;/*p_1每次后移一个节点p_2每次后移两个节点*/void fun_loop(A *head){A *p_1 = head;A *p_2 = head;while(p_2!=NULL){p_1 = p_1->next;p_2 = p_2->next->next;if(p_1 ==  p_2){printf("have loop!\n");return;}}printf("have no loop!\n");return;}/*说明:环形单向链表pf始终指向当前节点的前项节点,当链表中仅有一个节点时候pf=pb=head*/A *create(A *head,int n){int i;A *pb = head,*pf = NULL;for(i=0; i<n; i++){pb = (A *)malloc(sizeof(A));pb->data= i;/*当前节点pb作为头结点*/if(i == 0){head = pb;pb->next = head;pf = pb;}/*前项节点pf的next指向当前节点,最后前项节点再后移指向当前节点pb*/else{pf->next = pb;pb->next = head;pf = pb;}}return head;}void print(A *head){A *pi = head;while((pi!=NULL)&&(pi->next != head)){printf("the data is %d.\n",pi->data);pi = pi->next;}printf("the data is %d.\n",pi->data);}/*检查单向链表是否成环*/int main(int argc,char *argv[]){A *head = NULL;head = create(head,5);print(head);fun_loop(head);return 0;}


0 0
原创粉丝点击