输入一个升序的链表,插入一个值并保持升序
但输出的时候插入的值会到后面一位
这咋改
#include "slnklist.h"
void insert(linklist head,datatype x)
{
linklist p, q, s;
s=(linklist)malloc(sizeof(struct node));
s->data=x;
s->next=NULL;
q=head;
p=head->next;
while(p!=NULL&&p->data<=x)
{
q=p;p=p->next;
}
if(p)
{
s->next=p->next;
p->next=s;
}
else
{
s->next=q->next;
q->next=s;
}
}
main()
{
linklist L;
datatype a,b;
L=creatbyqueue();
printf("请输要插入的值:");
scanf("%d",&a);
insert(L,a);
print(L);
}
q=head;
p=head->next;
while(p!=NULL&&p->data<=x)
{
q=p;p=p->next;
}
if(p)
{
q->next = s;
s->next = p;
}
else
{
q->next = s;
}
这个链表带不带头结点的?带头结点的这么改,供参考:
void insert(LinkList head, int x)
{
LinkList p, q, s;
s = (LinkList)malloc(sizeof(Node));
s->data = x;
s->next = NULL;
q = head;
p = head->next;
while (p != NULL && p->data <= x)
{
q = p;
p = p->next;
}
s->next = q->next;
q->next = s;
}