循环链表
循环链表就是在单链表的基础上,尾节点总是指向头节点的。
如下图所示:
插入方式
只要是链表就存在两种插入放下,下面介绍循环链表的头插法,与尾插法。
头插法
循环链表的头插法与单链表的头插法相似。
- 假设链表中存在一个元素。
- 生成一个新元素,并在头节点后方插入。
- 插入完成。
尾插法
尾插法的方法也与单链表的尾插法类似,只不过尾节点要指向头节点罢了。
- 假设链表中有一个元素。
- 生成新节点,插入在尾节点之后,并且将新的尾节点指向头节点。
- 插入完成
C语言 实现
#include <stdio.h>
#include <assert.h>
typedef struct node
{
int data;
struct node* next;
}List;
void __list_init(List* head)
{
if (head == NULL)
{
printf("head is NULL\n");
assert(0);
}
else
{
List* temp = head;
temp->next = temp;
temp->data = -1;
}
}
List* __insert_element(List* head, int num)//尾插
{
if (head == NULL)
{
printf("head is NULL\n");
assert(0);
}
else
{
List* temp = head;
List* new_node = (List*)malloc(sizeof(List));
while (temp->next != head)
{
temp = temp->next;
}
new_node->data = num;
new_node->next = temp->next;
temp->next = new_node;
}
}
void __insert_element_one_by_one(List* head, int num) //头插
{
if (head == NULL)
{
printf("head is NULL\n");
assert(0);
}
else
{
List* temp = head;
List* new_node = (List*)malloc(sizeof(List));
new_node->data = num;
new_node->next = temp->next;
temp->next = new_node;
}
}
void __print_list(List* head)
{
if (head == NULL)
{
printf("head is NULL\n");
assert(0);
}
else
{
List* temp = head->next;
while (temp->next != head->next)
{
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
}
void __destory(List* head)
{
free(head);
}
int __delete_some_node(List* head, int data)
{
if (head != NULL)
{
List* fast = head->next;
List* slow = head;
while (fast != NULL)//如果 pre_node的下一个节点的数据等于我们寻找的数据
{
if (fast->data == data)
{
slow->next = fast->next;
free(fast);
return 1;
}
else
{
fast = fast->next;
slow = slow->next;
}
}
return 0;//can not found
}
else
{
printf("head is NULL\n");
return 0;
}
}
void __insert_element_behind_some_node(List* head, int num, int element)
{
if (head != NULL)
{
List* fast = head->next;
List* slow = head;
while (fast != NULL)
{
if (fast->data == num)
{
List* new_node = (List*)malloc(sizeof(List));
new_node->data = element;
new_node->next = fast->next;
fast->next = new_node;
break;
}
else
{
fast = fast->next;
slow = slow->next;
}
}
return;//can not found
}
else
{
printf("head is NULL\n");
return;
}
}
int main()
{
List* l = (List*)malloc(sizeof(List));
List* L = (List*)malloc(sizeof(List));
__list_init(l);
__list_init(L);
for (int i = 0; i < 10; i++)
{
printf("%d ", i);
__insert_element(l,i);//尾插法
__insert_element_one_by_one(L, i);//头插法
}
printf("\n");
printf("wei cha :");
__print_list(l);
printf("tou cha : ");
__print_list(L);
__delete_some_node(l, 3);
printf("wei cha de list:");
__print_list(l);
__insert_element_behind_some_node(L, 3, 100);
printf("tou cha de list :");
__print_list(L);
__destory(l);
__destory(L);
}