题目要求
问题:为什么当我要插入的是-1时,输出的结果最后-1 变成了0 ?
代码
```c
List Insert( List L, ElementType X ){
List head,p,q;
head=(struct Node*)malloc(sizeof(struct Node));//创建头指针
head->Next=L;
p=head;
q=(struct Node*)malloc(sizeof(struct Node));;//创建插入结点
q->Data=X;
//printf("%d\n",p->Data);
if(X<=p->Next->Data){
q->Next=p->Next;
p->Next=q;
p=p->Next;
return head->Next;
}
while(p->Next!=NULL){
if(X<=(p->Next->Data)&&X>p->Data){
q->Next=p->Next;
p->Next=q;
return head->Next;
};
p=p->Next;
}
q->Next=NULL;
p->Next=q;
return head->Next;}
修改如下,供参考:
typedef struct Node* PtrToNode;
struct Node{
int Data;
PtrToNode Next;
};
typedef PtrToNode List;
List Insert( List L, ElementType X )
{
List head,p,q;
p = L;
//head=(struct Node*)malloc(sizeof(struct Node));//创建头指针 //修改
//head->Next=L;
//p=head;
q = (struct Node*)malloc(sizeof(struct Node));;//创建插入结点
q->Data = X;
q->Next=NULL;
//printf("%d\n",p->Data); //修改
//if(X<=p->Next->Data){
// q->Next=p->Next;
// p->Next=q;
// p=p->Next;
// return head->Next;
//}
while(p->Next!=NULL && p->Next->Data < X){ //修改
p=p->Next;
}
q->Next = p->Next; //修改
p->Next = q; //修改
return L; //return head->Next;//修改
}
#include <stdio.h>
int Getfigures(int n) //统计整数n的位数
{
int count=0;
do
{
count++;
n/=10;
}while(n!=0);
return count;
}
/* int Getfigures(int n) //若要用此函数,则对0求其位数会出错,可加if-else语
句补缺。此方法采用while()语句,上面采用do-while() 语句,这就体现了while()语句
和do-while() 语句的区别,事实证明二者只在0和1上有区别。
{
int count=0;
while(n!=0)
{
count++;
n/=10;
}
return count;
}
*/