69,371
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <stdlib.h>
struct node
{
int num;
struct node* next;
};
struct node* create(int n)
{
struct node* head,*p, *point;
p = head = NULL;
int i;
for(i=0;i<n;i++)
{
point=(struct node*)malloc(sizeof(struct node));
if (!point)
exit(0);
point->num=i;
if(0==i)
{
head=point;
}
else
{
p->next=point;
}
p = point;
}
point->next=NULL;
return head;
}
struct node* insert_node(struct node* head,struct node* p) //插入节点,head为链表的头结点,p为需要插入的节点.
{
if (!head)
{
head = p;
p->next=NULL;
return head;
}
struct node* p1,*p2;
p1 = head;
while(p1 && p->num > p1->num)
{
p2 = p1;
p1 = p1->next;
}
if(p->num <= p1->num)
{
if(head == p1) /* head 和 p1比较,怎么可以和p比较呢*/
{
head = p;
p->next = p1;
}
else
{
p2->next = p;
p->next = p1;
}
}
else
{
p1->next = p;
p->next = NULL;
}
return head;
}
void show_nodes(struct node *head)
{
struct node* foreach;
for(foreach = head;foreach!=NULL;foreach = foreach->next)
{
printf("%d\t",foreach->num);
}
putchar(10);
}
int main()
{
struct node *head = create(9);
show_nodes(head);
struct node* pp = (struct node*)malloc(sizeof(struct node));
if (!pp)
return -1;
pp->num = -1;
head = insert_node(head, pp);
show_nodes(head);
return 0;
}
参考一下吧
有多出错误,建议对比查找原因。
比如:insert_node函数,如果插入的位置是head前,那么head就会被更新,就需要返回新的head。
for(foreach=head;foreach!=NULL;foreach->next=foreach)
{
printf("%d\t",foreach->num);
}
建议显示功能单独用一个函数实现。另外foreach->next=foreach应该改成foreach = foreach->next;
其他问题建议对比代码找原因,如果还有不明白的,可以继续提问