将数据元素b插入循环单链表Head中第一个元素为a的结点之前。
#include<stdio.h>
#include<malloc.h>
#define LNode sizeof(struct num)
struct num
{
char n;
struct num*next;
};
struct num*creat(void) //创造链表函数
{
struct num*head,*r,*s;
char n;
head=(struct num*)malloc(sizeof(struct num));
r=head;
scanf("%c",&n);
while(n!=0)
{
s=(struct num*)malloc(sizeof(struct num));
s->n=n;
r->next=s;
r=s;
scanf("%c",&n);
}
r->next=head;
return head;
}
struct num*print(struct num*head) //输出链表函数
{
struct num*p;
p=head->next;
while(p)
{
printf("%5c",p->n);
p=p->next;
}
printf("\n");
}
struct num*insert(struct num*head)
{
struct num*p,*q,*save;
if(head->next==head)
{
q=(struct num*)malloc(sizeof(struct num));
q->n='b';
head->next=q;
q->next=head;
}
else
{
p=head->next;
head->n='a';
}
while(p->n!='a')
{
save=p;
p=p->next;
}
q=(struct num*)malloc(sizeof(struct num));
q->n='b';
q->next=p;
save->next=q;
return head;
}
int main(void)
{
struct num*head,*p2;
head=creat();
print(head);
insert(head);
print(head);
return 0;
}
insert 里面,变量 `struct num*p` 在语句 ` while(p->n!='a')` 之前,如果分支进入` if(head->next==head)` 的情况,指针 p 并没有被初始化,此处就有问题。建议先对你的 `insert` 画一下程序的流程图,先把流畅梳理清楚。