写出一个将数据元素b插入到代表头节点的单链表第一个元素为a结点之前的算法。
#include<stdio.h>
#include<malloc.h>
#define len sizeof(struct num)
struct num
{
char n;
struct num*next;
};
struct num*creat(void)
{
struct num*head,*p1,*p2;
char chars[10]={'b','c','c','a','e','f','g','h','m','n'};
int i;
head=p2=(struct num*)malloc(len);
head->next=NULL;
p2=head;
for(i=0;i<10;i++)
{
struct num*p1;
p1=(struct num*)malloc(len);
p1->next=NULL;
p1->n=chars[i];
p2->next=p1;
p2=p1;
}
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*p1,*p2;
p1=head->next;
head->next=NULL;
int i=0;
while(i<10&&p1->n!='a')
{
p1=p1->next;
i++;
}
if(p1->n=NULL)
{
p2=(struct num*)malloc(len);
p2->n='b';
p2->next=p1->next;
p1->next=p2;
}
else
{
p1->n='b';
}
return head;
}
int main(void)
{
struct num*head,*p2;
head=creat();
print(head);
insert(head);
print(head);
return 0;
}
#include<stdio.h>
#include<malloc.h>
#define len sizeof(struct num)
struct num
{
char n;
struct num* next;
};
struct num* creat(void)
{
struct num *head,*p1,*p2;
char chars[10]={'b','c','c','a','e','f','g','h','m','n'};
int i;
head=p2=(struct num*)malloc(len);
head->next=NULL;
p2=head;
for(i=0;i<10;i++)
{
struct num*p1;
p1=(struct num*)malloc(len);
p1->next=NULL;
p1->n=chars[i];
p2->next=p1;
p2=p1;
}
return head;
}
void 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 *p1,*p2;
/*p1=head->next;
head->next=NULL; //这里把head.next指向了null,后续又没有还原,就变成最后返回的head只是一个n为空,next也为null的结构体而已
int i=0;
while(i<10 && p1->n!='a')
{
p1=p1->next;
i++; //以指针指向数据做判断就可以了,计数其实是多余的
}
//要将b节点插入到a节点之前,就要保存a的前一个节点
if(p1->n=NULL)
{
p2=(struct num*)malloc(len);
p2->n='b';
p2->next=p1->next;
p1->next=p2;
}
else
{
p1->n='b';
}
*/
p1 = head;
while(p1->next != NULL && p1->next->n != 'a'){
p1 = p1->next;
}
//两种情况:1.没有数据为a的节点,直接放到最后 2:有此节点,将其放在a的前一个节点之后 。操作都是一样的。
p2=(struct num*)malloc(len);
p2->n='b';
p2->next=p1->next;
p1->next=p2;
return head;
}
int main(void)
{
struct num* head,*p2;
head = creat();
print(head);
insert(head);
print(head);
return 0;
}
给你改了一点,只是可以运行,你的insert函数是在改写,而不是插入,这地方把指针画出来看看错在哪里了,自己改一改。(给你个提示,如果是插入在a节点之前,应该用p.next==a来判断是否找到,这样在你插在p的后面才是插入a之前的位置。就像是跑步你超过第二名之后你是第几名?)
void print(struct num*head)//打印函数,可以使用void,如果使用你之前的写法,请写一个return语句。
{
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*p1, *p2;
p1 = head->next;
//head->next = NULL; 为什么把headnext变成NULL?,head是头结点,不能改变的,headnext=null直接把整个链表删除了都
int i = 0;
while (i < 10 && p1->n != 'a')
{
p1 = p1->next;
i++;
}
if (p1->n == NULL)//这里是判断为空,而不是赋值为空
{
p2 = (struct num*)malloc(len);
p2->n = 'D';
p2->next = p1->next;
p1->next = p2;
}
else
{
p1->n = 'D';
}
return head;
}