码迷,mamicode.com
首页 > 其他好文 > 详细

循环链表

时间:2019-09-30 23:37:40      阅读:83      评论:0      收藏:0      [点我收藏+]

标签:div   next   efi   std   fine   The   span   def   col   

技术图片
  1 #include<bits/stdc++.h>
  2 using namespace std;
  3 #define sc scanf
  4 #define pr printf
  5 
  6 typedef struct LNode{
  7     int data;
  8     struct LNode *next;
  9 }LNode,*LinkList; 
 10 
 11 void Create_CircleList(LinkList &L,int n)
 12 {
 13     LNode *p,*q;
 14     L = (LNode *)malloc(sizeof(LNode));
 15     L->data = 0;
 16     L->next = NULL;
 17     
 18     //创建最后一个结点 
 19     q = (LNode *)malloc(sizeof(LNode));
 20     scanf("%d",&q->data);
 21     q->next = L->next;
 22     L->next = q;
 23     
 24     for(int i = 1;i < n;i++)
 25     {
 26         p = (LNode *)malloc(sizeof(LNode));
 27         scanf("%d",&p->data);
 28         p->next = L->next;
 29         L->next = p;
 30     }
 31     //因为是循环链表,所以最后一个结点的指针指向头结点 
 32     q->next = L;
 33     
 34 }
 35 
 36 //遍历循环链表  
 37 void Traver_CircleList(LinkList &L)
 38 {
 39   LNode *p = L;
 40   while(p->next != L)
 41   {
 42        p = p->next;
 43      cout << p->data << " "; 
 44   }    
 45   puts("");
 46 } 
 47 
 48 int getLength(LinkList &L)
 49 {
 50   LNode *p = L;
 51   int cnt = 0;
 52   while(p->next != L)
 53   {
 54        p = p->next;
 55      cnt++;
 56   }    
 57   return cnt;
 58 }
 59 
 60 //删除循环链表的某个结点
 61 bool Delete_Node(LinkList &L,int i,int &e)
 62 {
 63     int len = getLength(L);
 64     if(i < 1 || i > len || L->next == NULL)
 65     {
 66         puts("Oh! Baby! The position is invalid. Please re-enter the position!");
 67         return 0;
 68     }
 69     LNode *p = L;
 70     int j = 0;
 71     while(p->next != L && j < i - 1)
 72     {
 73            p = p->next;
 74          j++;
 75     }    
 76     
 77     LNode *q = (LinkList)malloc(sizeof(LNode));
 78     q = p->next;
 79     p->next = q->next;
 80     e = q->data;
 81     free(p);
 82     return 1;
 83 } 
 84 
 85 int main()
 86 {
 87     LNode *la;
 88     int n,m;
 89     scanf("%d%d",&n,&m);
 90     Create_CircleList(la,n);
 91     
 92     cout << "La length = " << getLength (la) << endl;
 93     Traver_CircleList(la);
 94     int e;
 95     bool ok = Delete_Node(la,1,e);
 96     if(ok)
 97     {
 98         cout << e << endl;
 99         cout << "after delete La length = " << getLength(la) << endl;
100         Traver_CircleList(la);
101     }
102     return 0;
103 }
View Code

 

循环链表

标签:div   next   efi   std   fine   The   span   def   col   

原文地址:https://www.cnblogs.com/mch5201314/p/11614246.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!