实现效果如下:
#includeusing namespace std; typedef int T; //循环链表 class Node { public: T data; Node* next; }; class CirLink { public: CirLink(); ~CirLink(); void InsertLink(); //尾插 void ValueInsert(); //任意位置插入指定值 void SortLink(); //排序 void ShowLink(); //显示 void ValueDelete(); //删除指定值 void FindLink(); //查找指定值 private: Node* head; Node* rear; T length; }; CirLink::CirLink() { head = new Node; rear = head; rear->next = head; length = 0; } void CirLink::InsertLink() { Node* ptemp = head; cout << "请向循环链表中输入数据:" << " "; rear = new Node; cin >> rear->data; cout << endl; rear->next = head->next; ptemp->next = rear; ptemp = ptemp->next; length++; } void CirLink::ValueInsert() //任意位置插入指定值 { int i, e = 0; Node* ptemp = new Node; cout << "请输入插入位置:" << " "; cin >> i; cout << endl; cout << "请输入插入数据:" << " "; cin >> ptemp->data; cout << endl; Node* qtemp = head; for (int j = 0; j < i - 1; j++) { qtemp = qtemp->next; } if ((qtemp->next)->next == head) { ptemp->next = head; (qtemp->next)->next = ptemp; } else { ptemp->next = qtemp->next; qtemp->next = ptemp; } ptemp = qtemp = NULL; length++; } void CirLink::SortLink() { Node* p, * q; p = head->next; while (p != head) { q = p->next; while (q != head) { if (p->data > q->data) { int e = p->data; p->data = q->data; q->data = e; } q = q->next; } p = p->next; } } void CirLink::ShowLink() { if (head->next == head) { cout << "空表!" << endl; } Node* ptemp = head->next; while (ptemp != head) { cout << "循环链表中的元素为:" << ptemp->data << " "; ptemp = ptemp->next; } cout << endl; } void CirLink::FindLink() { Node* p = head->next; int k = 1; cout << "输入查找值:" << " "; int e = 0; cin >> e; while ((p != head) && (p->data != e)) { p = p->next; k++; } if (p == head) { cout << "此数值不存在!" << endl; } else { cout << "此数值所在位置为:" << k << endl; } } void CirLink::ValueDelete() { Node* p = head->next; Node* q = head; int k = 1; cout << "输入删除值:" << " "; int e = 0; cin >> e; while ((p != head) && (p->data != e)) { p = p->next; q = q->next; k++; } if (p == head) { cout << "此数值不存在!" << endl; } else { q->next = p->next; delete p; p = NULL; cout << "此数值已删除!" << endl; length--; } } CirLink::~CirLink() { Node* ptemp = head->next; while (head->next != head) { head->next = ptemp->next; delete ptemp; ptemp = head->next; } rear = head; ptemp = NULL; } int main() { CirLink s; s.InsertLink(); s.InsertLink(); s.InsertLink(); s.InsertLink(); s.ShowLink(); s.ValueInsert(); s.ShowLink(); s.FindLink(); s.ValueDelete(); s.ShowLink(); system("pause"); return 0; }



