单链表是否有环问题

来源:互联网 发布:mac链接不上硬盘 编辑:程序博客网 时间:2024/05/17 03:53

有很多种方式解决问题,我这里只说一种方法

使用p、q两个指针,p每次向前走一步,q每次向前走两步,若在某时候p == q,则存在环,如图:



代码实现:

#include <stdio.h>#include <stdlib.h>#define LEN 8typedef struct node{char val;struct node *next;}*node_t;int has_loop2(node_t head);int main(){node_t* arr = (node_t*)malloc(sizeof(struct node)*LEN);arr[0] = (node_t)malloc(sizeof(struct node));int i;for(i = 1;i<LEN;i++){arr[i]=(node_t)malloc(sizeof(struct node));arr[i-1]->next = arr[i];}arr[LEN - 1]->next = NULL;if(has_loop2(arr[0]))printf("是环\n");elseprintf("不是环\n");return 0;}int has_loop2(node_t head){node_t p = head;node_t q = head;while(p!=NULL && q !=NULL){p = p->next;//p走一步if(q->next != NULL)q = q->next->next;//q走两步if(p == q)//如果相等则退出,否则继续走,直到重合return 1;p = p->next;q = q->next;if(q !=NULL)q = q->next;if(p!=NULL && p == q){return 1;}}return 0;}


原创粉丝点击