【申明:本文仅限于自我归纳总结和相互交流,有纰漏还望各位指出。 联系邮箱:Mr_chenping@163.com】
上一次我写过单向链表,单向循环链表和单向链表类似,仅仅是循环条件不同而已。
单向循环链表特点:
一、每个节点依旧跟单向链表一样,包含一个指向下一节点的指针。
二、最后一个节点不在指向NULL,指向第一个节点。
三、单向循环链表可以从任意一个节点出发遍历整个链表。
下面是代码,同单向链表类似没做太多改变,仅仅是遍历条件变化而已:
typedef struct _Sample_Circle_List
{
int Data;
struct _Sample_Circle_List *next;
}Sample_Circle_List;
Sample_Circle_List *Create_Link()
{
Sample_Circle_List *New;
New = (Sample_Circle_List *)malloc(sizeof(Sample_Circle_List));
if(New == NULL)
{
perror("Init malloc");
}
New->Data = -1;
New->next = New;
return New;
}
/*插入节点数据,按数据顺序插入*/
int Insert_Link(Sample_Circle_List *head, int valude)
{
Sample_Circle_List *current = head;
Sample_Circle_List *New; //申请新节点
New = (Sample_Circle_List *)malloc(sizeof(Sample_Circle_List));
if(New == NULL)
{
perror("malloc new");
}
New->Data = valude;
while((current->next != head) && (valude > current->next->Data))
{
current = current->next;
}
if(current->next == NULL) //第一个结点或者查找到最后
{
current->next = New;
New->next = NULL;
}
else //中间插入(注意:crrent和current->next是分别指向两个不同节点)
{
New->next = current->next;
current->next = New;
}
return 0;
}
/*删除节点*/
int Delete_Note(Sample_Circle_List *head, int valude)
{
Sample_Circle_List *history = head; //历史节点
Sample_Circle_List *current = head->next; //游动节点
while((current != head) && (current->Data != valude))
{
history = current;
current = current->next;
}
if(current == head) //等于NULL有两种情况:(1)查找到最后、(2)节点为空
{
if(head->next == head)
{
printf("List is empty!\n");
}
else
{
printf("Not find the Node!\n");
}
return -1;
}
else
{
history->next = current->next;
free(current);
printf("Delete Node success!\n");
}
return 0;
}
/*查找指定节点*/
int Search_Link(Sample_Circle_List *head, int key)
{
Sample_Circle_List *current = head->next;
while((current != head) && (current->Data != key))
{
current = current->next;
}
if(current == head) //链表为空或者没有查找到
{
if(head->next == head)
{
printf("Link is empty!\n");
}
else
{
printf("Not find!\n");
}
return -1;
}
else
{
printf("find it!\n");
}
return 0;
}
/*遍历链表*/
void Print_Link(Sample_Circle_List *head)
{
Sample_Circle_List *current = head->next;
printf("\nLink as fallows:\n");
while(current != head)
{
printf("%d-->", current->Data);
current = current->next;
}
printf("\n");
}
/*测定链表的长度,即有多少个结点*/
int Length_Link(Sample_Circle_List *head)
{
Sample_Circle_List *current = head->next;
int count = 0;
while(current != head)
{
count++;
current = current->next;
}
return count;
}
/*释放链表*/
void Free_Link(Sample_Circle_List *head)
{
Sample_Circle_List *current = head->next;
Sample_Circle_List *record = head;
while(current != head)
{
record = current;
current = current->next;
free(record);
}
free(head);
printf("Free Link success!");
exit(0);
}