单向循环链表与单链表的区别:
- 单向循环链表:
1.尾结点的指针域指向首结点,可以通过任意结点遍历整个链表
tail->next = head;
2.为空链表时,头结点指向自己
head->next = head;
- 单链表:
1.尾结点的指针域指向NULL,只可以通过头结点遍历整个链表
tail = NULL;
2.为空链表时,头结点指向NULL
head ->next = NULL;
单向循环链表的实现过程与单链表基本相似,只有几个操作需要在结尾处进行修改,下面写出几个简单的操作,具体可看单链表的代码
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
typedef int ElemType;
typedef struct CirNode{
ElemType data; // 数据域
struct CirNode * next; //指针域
}CirNode,*CirLinkList;
//因为使用void 所以用CircularLinkList *list,可以直接对指针地址内容进行修改,即对链表修改,类似于int*传参,直接修改内容
//CircularLinkList list相当于传参int x,没有传值不能修改内容,除非有返回值
CirLinkList InitCirLinkList()
{
CirNode *L;
L = (CirLinkList)malloc(sizeof(CirNode));
if(L == NULL)
cout << "申请空间失败!";
L->next = L;//空循环链表的头结点指向自己,而单链表是L->next = NULL;
return L;
}
void OutPut(CirLinkList L)
{
CirNode * p;
p = L->next;
cout << "此循环链表为:";
cout << p->data << " ";
p = p->next;
while(p!=L->next)//当p不是头结点时
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
void CreatCirLinkListHead(CirLinkList &L,int length)
{
CirLinkList node = NULL;
for(int i = 0;i <length;i++)
{
node = (CirLinkList)malloc(sizeof(CirNode));
cout << "输入第" << i+1<< "个元素:";
ElemType x;
cin >> x;
node->data = x;
node->next = L->next;
L->next= node;
}
}
void CreatCirLinkListTail(CirLinkList &L,int length)
{
CirLinkList node = NULL;
CirLinkList tail = NULL;
tail = L;
for(int i = 0;i < length;i++)
{
node = (CirLinkList)malloc(sizeof(CirNode));
cout << "输入第" << i+1<< "个元素:";
ElemType x;
cin >> x;
node->data = x;
tail->next = node;
tail = node;
tail->next = L->next;//尾结点指向头指针
}
}
bool IsEmpty(CirLinkList L)
{
if(L->next == L)
return true;
else return false;
}
void insertCirLinkList(CirLinkList &L,int pos,ElemType element)
{
CirLinkList p = L;
int j = 1;
while(j < pos)
{
p = p->next;
j++;
}
CirLinkList node;
node = (CirLinkList)malloc(sizeof(CirNode));
node->data = element;
node->next = p->next;
p->next = node;
}
CirLinkList GetNode(CirLinkList L,ElemType element)//通过数据得到结点
{
CirLinkList p;
p = L;
while(1)
{
p = p->next;
if(p->data == element)
return p;
}
}
void PrintCirNode(CirLinkList L,CirLinkList node)//从任意结点node开始,遍历整个循环链表(注意尾结点要和头指针相连,而不是头结点,在尾插法中有修改,在头插法中直接指向头结点了,这样在遍历的时候会打印头结点(为空))
{
CirLinkList p = node;
cout << p->data << " ";
p = p->next;
while(p != node)
{
cout << p->data << " ";
p = p->next;
}
}
int main()
{
CirLinkList L=(CirLinkList) malloc(sizeof(CirNode));
int length;
cout << "请输入循环链表的长度(头插法):";
cin >> length;
CreatCirLinkListHead(L,length);
OutPut(L);
cout << "请输入循环链表的长度(尾插法):";
cin >> length;
CreatCirLinkListTail(L,length);
OutPut(L);
int element;
cout << "请输入要插入的元素:";
cin >> element;
cout << "插入的位置:";
int position;
cin >> position;
insertCirLinkList(L,position,element);
OutPut(L);
cout << "请输入要从哪个元素开始搜索:";
cin >> element;
CirLinkList node = GetNode(L,element);
PrintCirNode(L,node);
return 0;
}