循环链表
Posted mch5201314
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了循环链表相关的知识,希望对你有一定的参考价值。
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
以上是关于循环链表的主要内容,如果未能解决你的问题,请参考以下文章