操作只需要把原来链表的判空=NULL改为不等于头结点即可
代码如下:
/*循环链表其实就是把链表的指向表尾结点的判断条件改变
变成了p!=L或则p->next!=L
*/
#include <stdio.h>
#include<stdlib.h>
typedef int elemtype;
typedef struct node
{
elemtype data;
struct node* next;
}node,*Node;
//初始化
int Initlist(node** head1)
{
*head1 = (node*)malloc(sizeof(node));
(*head1)->next = (*head1); //这里不再指向NULL
}
//插入
int insert(node* head1, int i, elemtype x)
{
node* p, * q;
int j=0;
p = head1;
while (j < i - 1 && p->next!=(head1)) //到i-1个元素
{
p = p->next; j++;
}
if (j == i - 1)
{
q = (node*)malloc(sizeof(node));
q->data = x;
q->next = p->next;
p->next = q;
}
}
//删除
int delete(node* head1, int i, elemtype* x)
{
int j = 0;
node* p, * q;
p = head1;
q = (node*)malloc(sizeof(node));
while (j < i - 1 && (p->next != head1))
{
p = p->next;
j++;
}
if (j == i - 1)
{
q = p->next;
*x = q->data;
p->next = q->next;
free(q);
}
return 1;
}
//尾插法
int bottominsert(node* head1,int j,int x)
{
int i = 0;
node* p, * q;
p = head1;
for (; i < j; i++,x++)
{
q = (node*)malloc(sizeof(node));
q->data = x;
p->next = q;
q->next = NULL;
p = q;
}
p->next = head1;
}
//打印
node* outlist(node* head1)
{
node* p = head1->next;
do
{
printf("%5d", p->data);
p = p->next;
} while (p != head1);
return head1;
}
int main()
{
Node head1;
Initlist(&head1); //初始化
bottominsert(head1,5,0); //建立循环链表
outlist(head1);
printf("\n");
int x = 100;
int i=0;
scanf_s("%d",&i);
insert(head1, i,x); //插入
outlist(head1);
printf("\n");
scanf_s("%d",&i);
delete(head1,i,&x); //删除
outlist(head1);
return 1;
}
运行结果如下: