判断一个链表是不是循环链表
算法思想:在建立循环链表时设置两个指针,头指针和尾指针,head和tail,使tail->next=head,即让尾节点指向头节点,建立的时候采用尾插入法,每次让新节点先指向尾节点的下一个节点,
然后让头节点的下一个节点指向新节点,然后让新节点赋值给头节点和尾节点。
判断是否是循环链表时,也设置两个指针,慢指针和快指针,让快指针比慢指针每次移动快两次。如果快指针追赶上慢指针,则为循环链表,否则不是循环链表,如果快指针或者慢指针指向NULL,则不是循环链表。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 | include <iostream> #include <cstdlib> using namespace std; typedef struct list { int data; struct list *next; }loopNode,*lpNode; void createList(lpNode &list, int arr[], int n) //创建循环链表 { lpNode node; lpNode head=NULL,tail=NULL; head=tail=list; tail->next=head; for ( int i=0;i<n;i++) { node=( struct list*) malloc ( sizeof ( struct list)); node->data=arr[i]; node->next=tail->next; head->next=node; head=node; tail=node; } cout<< "create success" <<endl; } int judgeIsLoop(lpNode list) //判断是否是循环链表 { if (list==NULL) return 0; lpNode slow,fast; slow=list; fast=list->next->next; while (slow) { if (fast==NULL||fast->next==NULL) return 0; else if (fast==slow||fast->next==slow) return 1; else { slow=slow->next; fast=fast->next->next; } } return 0; } void display(lpNode list) //输出循环链表 { lpNode head,tail; head=tail=list; while (head->next!=tail) { cout<<head->data<< "--" ; head=head->next; } cout<<head->data; cout<<endl; } int main() { lpNode list=NULL; int arr[10]={1,2,3,4,5,6,7,8,9,0}; int flag=0; list=( struct list*) malloc ( sizeof ( struct list)); list->data=11; list->next=NULL; createList(list,arr,10); flag= judgeIsLoop(list); if (flag==1) //如果是循环链表,就输出循环链表 { cout<< "the list is loop list." <<endl; cout<< "output the list:" <<endl; display(list); } else { cout<< "the list is not loop list." <<endl; } cout<<endl; return 0; } |
运行截图:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· [AI/GPT/综述] AI Agent的设计模式综述
2013-03-10 坚持的力量 第四篇
2013-03-10 坚持的力量 第三篇
2013-03-10 坚持的力量 第二篇
2013-03-10 坚持的力量 第一篇
2013-03-10 坚持的力量