循环链表的操作和应用

来源:互联网 发布:139邮箱 ssl端口 编辑:程序博客网 时间:2024/05/17 07:11

一、循环链表的定义和操作

循环链表的特点是,尾部节点的link(或next)域指向头节点而不是空(null)。这里定义的循环链表使用一个ptr指针成员指向链表的尾部节点。如图所示:


下面给出循环链表的具体定义和操作:

#define NULL 0#include<iostream>using namespace std;//#include <queue>class CircularList;class CNode{friend class CircularList;public:CNode(int n,CNode* l){info = n;next = l;}private:int info;CNode* next;};class CircularList{public:CircularList(CNode* p = NULL){ ptr = p;}void insertAtLeft(int i){CNode* newNode = new CNode(i,NULL);if(isEmpty()) ptr = newNode->next = newNode;else{newNode->next = ptr->next;ptr->next = newNode;}}void insertAtRight(int i){insertAtLeft(i);ptr = ptr->next;}void deleteAtLeft(){if(! isEmpty()){CNode* p = ptr->next;ptr->next = p->next;if(ptr == p) ptr = NULL;delete p;p = NULL;}else cout<<"链表为空,不能进行删除操作!"<<endl;}void eraseList(){if(isEmpty()) cout<<"链表为空,不能进行删除操作!"<<endl;else{CNode* p = ptr->next;//从头结点开始删除ptr->next = NULL;ptr = NULL;while(p != NULL){CNode* temp = p->next;delete p;p = temp;temp = NULL;}}}    void disjointTwoLists(CNode* ptr1){if(ptr1 != NULL){if(ptr != NULL){//交换两个表ptr的值CNode* temp = ptr->next;ptr->next = ptr1->next;ptr1->next = temp;}ptr = ptr1;    ptr1 = NULL;}}bool isEmpty(){ return ptr == NULL;}void printList(){if(isEmpty()){cout<<"链表为空,没有可以输出的内容!"<<endl;return;}CNode* p = ptr->next;while(p != ptr){cout<<p->info<<" ";p = p->next;}cout<<ptr->info<<endl;}CNode* getPtr(){ return ptr;}private:CNode* ptr;};

从代码中可以看出,循环链表的操作有(1)从左边插入节点(2)从右边插入节点(3)从左边删除节点(4)删除整个链表(5)合并两个循环链表(6)判断链表是否为空(7)输出链表每个节点的信息。注意这些操作都要考虑链表 为空的情况。

事实上,操作(1)和(3)实现了栈的功能;而操作(2)和(3)实现了队列的功能。

未完待续。



原创粉丝点击