int InsertListInOrder(LinkList L, ElemType x)
{ Node *s;
s=(Node *)malloc(sizeof(Node));
if (s==NULL) return ERROR;
s->data=x;
L=L->next;
while ( L!=NULL )
if ( x>L->data )
L=L->next;
else
{ s->next=L->next;
L->next=s;
}
return OK;
}
用多一个指针pre记录L当前遍历的上一个结点,遇到L>=x的时候,就把s插入到pre和L中间。
int InsertListInOrder(LinkList L, ElemType x)
{
Node *s, *pre;
s = (Node *)malloc(sizeof(Node));
if (s == NULL) return ERROR;
s->data = x;
pre = L;
L = L->next;
while (L != NULL) {
if (x > L->data) {
pre = L;
L = L->next;
}
else{
//把s插入到pre和L中间
s->next = L;
pre->next = s;
return OK;
}
}
//这里考虑L中没有大于等于x情况,也就是插入到末尾
s->next = L;
pre->next = s;
return OK;
}