线性表之单循环链表

//sList
#include <stdio.h>
#include <stdlib.h>

//===============状态量====================
#define OK 1
#define ERROR 0

//===================ADT 循环单链表 ===============
typedef int ElemType;
typedef struct CLNode{
ElemType data;
struct CLNode *next;
}CListNode;
typedef CListNode *CLinkList;

//================================模块定义==============================
//内置申请节点函数
static CLinkList newNode(){
CLinkList p = (CLinkList)malloc(sizeof(CListNode));
if(p != NULL)
p->next = NULL;
return p;
}

//初始化
void InitList(CLinkList *L){
(*L) = newNode();
if(*L == NULL){
fprintf(stderr, "初始化失败！\n");
exit(EXIT_FAILURE);
}
(*L)->next = (*L);
}

//销毁表
void DestroyList(CLinkList L){
CLinkList p = L;
CLinkList q = p->next;
while(q != L){
free(p);
p = q;
q = p->next;
}
free(p);
}

//判断表空
int ListEmpty(CLinkList L){
return (L->next == L);
}

//求表长
int ListLength(CLinkList L){
CLinkList p = L;
int i = 0;
while(p->next != L){
i++;
p = p->next;
}
return i;
}

//输出表
void DispList(CLinkList L){
CLinkList p = L->next;
while(p != L){
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}

//求下标为 i 的元素
int GetElem(CLinkList L, int i, ElemType *e){
int j = 0;
CLinkList p = L;
while(j < i && p->next != L){
p = p->next;
}
if(p == NULL)
return ERROR;
else{
*e = p->data;
return OK;
}
}

//求元素的下标
int LocateElem(CLinkList L, ElemType e){
int j = 0;
CLinkList p = L;
while(p->next != L && p->data != e){
j++;
p = p->next;
}
if(p == L)
return ERROR;
else
return j;
}

//插入元素
int InsertList(CLinkList L, int i, ElemType e){
CLinkList p = L;
CLinkList pNew = NULL;
int j = 0;

if(p->next == L || i == 1){                                 //原链表为空表或者 i = 1时
pNew = newNode();
pNew->data = e;
pNew->next = p->next;                                    //因p的指针域会改变所以先连接后面
p->next = pNew;
return OK;
}
else{
p = L->next;
while(j < i - 2 && p != L){                     //查找前驱节点
j++;
p = p->next;
}
if(p == L)                                           //i 输入错误
return ERROR;
else{
pNew = newNode();
pNew->data = e;
pNew->next = p->next;
p->next = pNew;
return OK;
}
}
}
//删除元素
int DeleteList(CLinkList L, int i, ElemType *e){
int j = 0;
CLinkList p = L;
CLinkList q = NULL;

if(p->next == L){                                             //为空表时
return ERROR;
}
else{
if(i == 1){
q = p->next;
*e = q->data;
p->next = q->next;
free(q);
return OK;
}//if
else{
p = L->next;
while(j < i - 2 && p != L){
j++;
p = p->next;
}
if(p == L)
return ERROR;
else{
q = p->next;
*e = q->data;
p->next = q->next;
free(q);
return OK;
}
}//else
}//else
}