printf("\ninsert number:\n");
scanf("%d",&number);
Node *n=(Node*)malloc(sizeof(Node));
n->data=number;
pre=head;
p=head->next;
while(p!=NULL)
{
if(n->data<pre->data)
head->next=n;
if((n->data<=p->data)&&(n->data>=pre->data))
{
pre->next=n;
n->next=p;
}
else
{
pre=p;
p=p->next;
}
}
给一个已经升序排列的链表(带头结点)插入一个值,使其顺序不变。应该是while那里出问题了,可以看下哪里出错了吗
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
2条回答 默认 最新
qzjhjxj 2021-11-30 14:21关注供参考:
void insert(Node*& head) { int number; Node* pre, * p; printf("\ninsert number:\n"); scanf("%d", &number); Node* n = (Node*)malloc(sizeof(Node)); n->data = number; n->next = NULL; pre = head; p = head->next; while (p != NULL) { if (n->data <= p->data) { n->next = pre->next; pre->next = n; break; } pre = p; p = p->next; } }本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报