#include <stdio.h>
#include <stdlib.h>/**
* 含头节点循环单链表定义,初始化 及创建
*/#define OK 1;
#define ERROR 0;//函数返回类型,表示函数运行结果的状态
typedef int Status;
//定义数据元素类型
typedef char ElemType;//循环单链表定义
typedef struct LoopLnode {
ElemType data; //数据域,这里是char类型变量
struct LoopLnode *next; //指针域,结构体类型指针
} LoopLnode, *LoopLinkList;//循环单链表初始化
Status InitList(LoopLinkList *list) {
(*list)=(LoopLinkList)malloc(sizeof(LoopLnode));
(*list)->next=(*list);
(*list)->data='T'; //测试用,可不写
return OK;
}//1."头插法"创建仅含"头指针"的单向循环链表
Status CreateList_H(LoopLinkList *list,ElemType arrData[],int length){
int j;
for(j=length-1;j>=0;j--){
//新建结点
LoopLnode *node;
node=(LoopLnode*)malloc(sizeof(LoopLnode));
node->data=arrData[j];
node->next=NULL; //插入循环链表
node->next=(*list)->next;
(*list)->next=node; //list始终指向头结点
}
return OK;
}//2."尾插法"创建仅含"头指针"的单向循环链表
Status CreateList_R(LoopLinkList *list,ElemType arrData[],int length){
LoopLnode *r;
r=*list;
int j;
for(j=0;j<length;j++) {
//新建结点
LoopLnode *node;
node=(LoopLnode*)malloc(sizeof(LoopLnode));
node->data=arrData[j];
node->next=NULL; //插入循环链表
node->next=r->next;
r=node;
}
return OK;
}//3."头插法"创建仅含"尾指针"的单向循环链表
Status BuildList_H(LoopLinkList *list,ElemType arrData[],int length){
int j;
for(j=length-1;j>=0;j--){
//新建结点
LoopLnode *node;
node=(LoopLnode*)malloc(sizeof(LoopLnode));
node->data=arrData[j];
node->next=NULL; //node插入1号结点,list为尾指针
node->next=(*list)->next->next; //node->next=头结点->next
if((*list)->next==(*list)) (*list)=node; //当只有头结点时(插入第一个结点时,手动设置node为尾指针)
(*list)->next->next=node; //头结点->next=node;
}
return OK;
}//4."尾插法"创建仅含"尾指针"的单向循环链表
Status BuildList_R(LoopLinkList *list,ElemType arrData[],int length) {
int j;
for(j=0;j<length;j++) {
//新建结点
LoopLnode *node;
node=(LoopLnode*)malloc(sizeof(LoopLnode));
node->data=arrData[j];
node->next=NULL; node->next=(*list)->next; //node->next=头结点
(*list) = node; //尾指针 —> node
}
return OK;
}int main(void){
//产生待插入到链表的数据
ElemType data1='A',data2='B',data3='C';
ElemType waitInserted[]={data1,data2,data3,};
//获得数组长度
int arrLength=sizeof(waitInserted)/sizeof(waitInserted[0]); /**1.头插法建立只含头指针循环单链表**/
//定义链表并初始化
LoopLinkList list1;
InitList(&list1);
//按既定数据建立链表
CreateList_H(&list1,waitInserted,arrLength);
//测试
printf("%c\n",list1->next->next->next->next->next->next->data); //B /**2.尾插法建立只含头指针循环单链表**/
//定义链表并初始化
LoopLinkList list2;
InitList(&list2);
//按既定数据建立链表
CreateList_R(&list2,waitInserted,arrLength);
//测试
printf("%c\n",list1->next->next->next->next->next->next->data); //B /**3.头插法建立只含尾指针循环单链表**/
//定义链表并初始化
LoopLinkList list3;
InitList(&list3);
//按既定数据建立链表
BuildList_H(&list3,waitInserted,arrLength); //list3指向表尾
//测试
printf("%c\n",list3->next->next->next->next->next->next->next->next->next->data); //T /**4.尾插法建立只含尾指针循环单链表**/
//定义链表并初始化
LoopLinkList list4;
InitList(&list4);
//按既定数据建立链表
BuildList_H(&list4,waitInserted,arrLength); //list4指向表尾
//测试
printf("%c\n",list4->next->next->next->next->next->next->next->next->next->next->data); //A printf("\nEND!");
return 0;
}