循环链表的创建及遍历

本文介绍了一种使用C++实现循环链表的方法,并提供了完整的源代码示例。包括循环链表的创建与遍历过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://blog.csdn.net/v_yang_guang_v/article/details/44906729

[cpp]  view plain  copy
  1. #include<iostream>  
  2. using namespace std;  
  3.   
  4. typedef int ElemType;  
  5.   
  6. typedef struct Node  
  7. {  
  8.     ElemType elem;  
  9.     struct Node *next;   
  10. }Node,*linklist;  
  11.   
  12. //创建循环链表  
  13. Node *createList(Node *head,int n)  
  14. {  
  15.     Node *p;  
  16.     for(int i=1;i<=n;i++)  
  17.     {  
  18.         p=(Node*)malloc(sizeof(Node));  
  19.         ElemType a;  
  20.         if(!p)  
  21.         {  
  22.             cout<<"内存分配失败"<<endl;  
  23.             exit(0);  
  24.         }  
  25.         cin>>a;  
  26.         p->elem=a;  
  27.         p->next=head->next;  
  28.         head->next=p;  
  29.     }  
  30.     return head;  
  31. }  
  32.   
  33.   
  34. //遍历循环链表  
  35. void printList(Node *head)  
  36. {  
  37.     Node *p;  
  38.     p=head->next;  
  39.     while(p!=head)  
  40.     {  
  41.         cout<<p->elem<<endl;  
  42.         p=p->next;  
  43.     }  
  44. }  
  45.   
  46. void main()  
  47. {  
  48.     Node *head,*p,*q;  
  49.     head=(Node*)malloc(sizeof(Node));  
  50.     if(!head)  
  51.     {  
  52.         cout<<"内存分配失败"<<endl;  
  53.         exit(0);  
  54.     }  
  55.     head->next=head;  
  56.     createList(head,4);  
  57.     printList(head);  
  58.     system("pause");  
  59. }  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值