循环链表是在单向链表的基础上,将尾节点指回头结点。
结果如图:#include<iostream> using namespace std; typedef int ELemtype; typedef struct CLNode { //循环链表的节点 ELemtype elem; struct CLNode *next; }*CLList; void init_List(CLList Head) { //初始化链表,使的next指针指向本身 Head->elem = NULL; Head->next = Head; } void Creat_List(CLList Head) { //创建链表 int elem = 1; CLList p = Head; while (elem) { cout << "Please enter the element you wanna insert(0 for end):"; cin >> elem; if (elem) { CLList node; node = (CLNode *)malloc(sizeof(CLNode)); if (p->elem == NULL) p->elem = elem; //链表为空是进行 else { CLList node; node = (CLNode *)malloc(sizeof(CLNode)); node->elem = elem; p->next = node; node->next = Head; p = p->next; } } } } int GetLength(CLList L) { //求链表长度 int len=0; CLList p = L; if (p->elem == NULL)return 0; p = p->next; ++len; while (p != L) { ++len; p = p->next; } return len; } void insert_Node(CLList L, ELemtype elem, int pos) { //在指定位置插入指定元素 if (L->elem == NULL) { cout << "The list is empty!" << endl; return; } int len = GetLength(L); if (pos <= 0 || pos > len) { cout << "The position is wrong!" << endl; return; } CLList p=L; CLList node; node = (CLNode *)malloc(sizeof(CLNode)); node->elem = elem; if (pos == 1) { for (int i = 1; i < len; ++i)p = p->next; } else { for (int i = 1; i < pos - 1; ++i)p = p->next; } node->next = p->next; p->next = node; } CLList delete_Node(CLList L, int pos) { //删除指定位置上的元素 if (L->elem == NULL) { cout << "The list is empty!" << endl; return L=NULL; } int len = GetLength(L); if (pos <= 0 || pos > len) { cout << "The position is wrong!" << endl; } CLList p = L; CLList temp; if (pos == 1) { p = p->next; while (p->next != L)p = p->next; temp = L; L = L->next; p->next = L; } else { for (int i = 1; i < pos - 1; ++i)p = p->next; temp = p->next; p->next = p->next->next; } delete temp; return L; } void output_List(CLList L) { //遍历链表 CLList p = L; if (p->elem == NULL) { cout << "This is a empty list!" << endl; } else { cout << p->elem << " "; p = p->next; while (p != L) { cout << p->elem << " "; p = p->next; } cout << endl; } } void test() { CLList L; L = (CLNode *)malloc(sizeof(CLNode)); init_List(L); Creat_List(L); output_List(L); cout << "len=" << GetLength(L) << endl; insert_Node(L, 36, 3); output_List(L); L=delete_Node(L, 1); output_List(L); } void main() { test(); system("pause"); }