1.定义
在单链表中,如果将终端结点的指针域有空指针指向头结点,则整个链表称为一个环,这种头尾相接的单链表称为循环单链表,简称循环链表。
2.代码
1 #include <iostream> 2 using namespace std; 3 struct Node 4 { 5 int data; 6 Node *next; 7 }; 8 class CLL 9 { 10 public: 11 CLL(int a[], int n); //建立有n个元素的循环单单链表 12 int Length(); 13 void PrintList(); //遍历单链表,按序号依次输出各元素 14 void Insert(int i, int x); 15 int Get(int i); 16 int Delete(int i); 17 private: 18 Node *first; //循环单链表的头指针 19 }; 20 CLL::CLL(int a[], int n) 21 { 22 first = new Node; 23 first->next = first; //初始化一个空循环链表 24 for (int i = 0; i<n; i++) 25 { 26 Node *s; 27 s = new Node; //为每个数组元素建立一个结点 28 s->data = a[n-i-1]; 29 s->next = first->next; 30 first->next = s; //s插入到循环链表中 31 } 32 } 33 void CLL::PrintList() 34 { 35 Node *p; 36 p = first->next; 37 while (p != first) 38 { 39 cout << p->data << " "; 40 p = p->next; 41 } 42 cout << endl; 43 } 44 void main() 45 { 46 int r[5] = { 1, 9, 7, 2, 5 }; 47 CLL L(r, 5); 48 cout << "线性表的数据为:" << endl; 49 L.PrintList(); 50 }