循环链表的基本操作的实现
特点:循环链表可以从任意一个位置循环遍历整个链表,如果设置的的为尾指针的话,其操作头节点后为节点的时间复杂度外O(1);
其实现代码如下
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef int ElementType;
typedef struct Node {
ElementType element;
struct Node *next;
} LNode, *CLinkList;
//***********基本操作*****************
CLinkList Init_LinkList();
bool Head_ListInsert(CLinkList L, ElementType e);
CLinkList Tail_ListInsert(CLinkList L, CLinkList P, ElementType e);
void PrtList(CLinkList L);
int List_Length(CLinkList L);
bool Delete_ListNode(CLinkList L, int locate);
int GetLocate(CLinkList L, ElementType e);
//**************#end*****************
int main() {
CLinkList list = Init_LinkList();
CLinkList point = list;
for (int i = 0; i < 5; ++i) {
point = Tail_ListInsert(list, point, i + 1);
}
printf("%d\n", List_Length(list));
Delete_ListNode(list, 3);
printf("%d\n", GetLocate(list, 3));
PrtList(list);
return 0;
}
//***********基本操作实现**************
CLinkList Init_LinkList() {
CLinkList NewNode = (CLinkList) malloc(sizeof(LNode));
NewNode->next = NewNode;
return NewNode;
}
bool Head_ListInsert(CLinkList L, ElementType e) {
CLinkList NewNode = (CLinkList) malloc(sizeof(LNode));
if (NewNode == NULL) {
printf("Memory is full!!");
return false;
}
NewNode->element = e;
NewNode->next = L->next;
L->next = NewNode;
return true;
}
CLinkList Tail_ListInsert(CLinkList L, CLinkList P, ElementType e) {
CLinkList NewNode = (CLinkList) malloc(sizeof(LNode));
if (NewNode == NULL) {
printf("Memory is full!!\n");
return false;
}
NewNode->element = e;
P->next = NewNode;
P = NewNode;
P->next = L;
return P;
}
int List_Length(CLinkList L) {
int counter = 0;
CLinkList P = L;
while (P->next != L) {
P = P->next;
counter++;
}
return counter;
}
void PrtList(CLinkList L) {
CLinkList P = L;
while (P->next != L) {
P = P->next;
printf("%d->", P->element);
}
}
int GetLocate(CLinkList L, ElementType e) {
int index = 1;
CLinkList P = L;
while (P->next != L) {
P = P->next;
if (P->element == e) {
return index;
}
index++;
}
return printf("Not find the element!!");
}
bool Delete_ListNode(CLinkList L, int locate) {
if (List_Length(L) < locate) {
printf("Not find the locate in list!!\n");
return false;
}
CLinkList P = L;
CLinkList TempCell = NULL;
while (locate > 1) {
P = P->next;
locate--;
}
TempCell = P->next;
P->next = TempCell->next;
free(TempCell);
return true;
}