首先所有的操作都需要两个头文件#include <stdio.h>和#include <stdlib.h>
1、定义结构体变量
typedef struct Node//定义结构体变量
{
int data;
struct Node *next;
}Node;
2、初始化链表
Node *iniList()
{
Node *L = (Node *)malloc(sizeof(Node));//申请空间
L->data = 0;//头节点data域表明该链表有多少元素,初试为0
L->next = L;//循环链表,因此头指针指向它自己
return L;
}
3、头插法建立循环单链表
void headList(Node *L,int data)
{
Node *node = (Node *)malloc(sizeof(Node));//申请新节点
node->data = data;//写入数据
node->next = L->next;//node指针指向L的下一个节点
L->next = node;//头节点指向node
}
4、尾插法建立循环单链表
void tailList(Node *L,int data)
{
Node *node = (Node *)malloc(sizeof(Node));//申请新节点
node->data = data;//新数据写入新节点
Node *tail = L;//设置尾节点
while(tail->next!=L)//循环遍历链表找到链表尾部
{
tail = tail->next;
}
node->next = tail->next;//插入尾节点后面
tail->next = node;//尾节点指向新节点
}
5、删除节点
int deletList(Node *L,int data)
{
Node *pre = L;//设置前驱节点
Node *current = L->next;//设置当前节点
while(current!=L)//遍历到最后节点停下(循环链表,最后节点也就是头节点的前一个节点)
{
if(current->data==data)
{//删除
pre->next = current->next;//前驱节点指向跳过当前节点直接指向下下一个节点
free(current);//释放当前节点
return 0;
}
pre = current;//没找到则两个节点都往后走一步
current = current->next;
}
return 1;
}
6、遍历输出
void printList(Node *L)
{
Node *head = L;//由于是循环链表,因此需要一个表明头部的指针
L = L->next;//从头节点的下一个开始
while(L!=head)//指针不断后移,当指针和head指针重合时说明已经遍历一遍了
{
printf("%d ",L->data);
L = L->next;//指针后移
}
printf("\n");
}
7、main函数测试各个模块
int main()
{
int i,n;
Node *head = iniList();//初始化链表
for(i=0;i<=5;i++)
headList(head,i);//测试头插法函数
for(i=6;i<=10;i++)
tailList(head,i);//测试尾插法函数
printList(head);//测试遍历输出函数
n = deletList(head,4);//测试删除函数
if(n==0)
printList(head);
else
printf("false!\n");
return 0;
}