程序能运行,但算法有错误!!
怎么也得不了正确结果, 我感觉void ListInsert2(Sqlist *L) 有错误!!
调了好长时间还是不行,帮帮忙!
#include <stdio.h>
#include <malloc.h>
#define LISTSIZE 10
typedef struct
{
int *elem;
int length;
int listsize;
}SqList;
void InitList(SqList *L);
void DestroyList(SqList *L);
int ListEmpty(SqList *L);
int ListLength(SqList *L);
int GetElem(SqList *L, int i, int *e);
void ListInsert(SqList *L, int n);
void ListInsert2(SqList *L, int i, int e);
int ListDelete(SqList *L, int i, int *e);
void Print(SqList *L);
int main(void)
{
int k, length, e1, e2, z;
SqList L;
InitList(&L);
ListInsert(&L, LISTSIZE - 1);
Print(&L);
ListInsert2(&L, 2, 20);
Print(&L);
z = ListDelete(&L, 3, &e1);
k = GetElem(&L, 4, &e2);
Print(&L);
length = ListLength(&L);
printf("z = %d\n",z);
printf("k = %d\n",k);
printf("length = %d\n",length);
Print(&L);
ListInsert2(&L, 2, 4);
Print(&L);
length = ListLength(&L);
printf("length = %d\n",length);
return 0;
}
void InitList(SqList *L)
{
(*L).elem = (int*)malloc(LISTSIZE * sizeof(int));
if (!(*L).elem) exit(1);
(*L).length = 0;
(*L).listsize = LISTSIZE;
}
void DestroyList(SqList *L)
{
if ((*L).elem == NULL) exit(1);
free((*L).elem);
(*L).elem = NULL;
}
int ListEmpty(SqList *L)
{
if ((*L).elem == NULL) exit(1);
if ((*L).length == 0) return 0;
else return 1;
}
int ListLength(SqList *L)
{
if ((*L).elem == NULL) exit(1);
return (*L).length;
}
int GetElem(SqList *L, int i, int *e)
{
if ((*L).elem == NULL) exit(1);
if (i<1 || i>((*L).length + 1)) return -1;
e = &(*L).elem[i];
return *e;
}
void ListInsert(SqList *L, int n)
{
int i;
if ((*L).elem == NULL) exit(1);
for (i = 0; i < n; i++)
{
printf("Enter one number:\n");
scanf("%d",&(*L).elem[i]);
++(*L).length;
}
}
void ListInsert2(SqList *L, int i, int e)
{
int *p,j,*q;
if ((*L).elem == NULL) exit(1);
if (i<1 || i>((*L).length + 1)) exit(1);
p = &(*L).elem[(*L).length - 1];
for (j = (*L).length -1; j >= i-1; --j)
{
*(p + 1) = *p;
}
q = &(*L).elem[i];
*q = e;
}
int ListDelete(SqList *L, int i, int *e)
{
int *p;
int j;
if ((*L).elem == NULL) exit(1);
if (i<1 || i>((*L).length +1)) exit(1);
*e = (*L).elem[i];
p = &(*L).elem[i];
for (j = i+1; j <((*L).length - 1); ++j)
{
*(p - 1) = *p;
}
--(*L).length;
return *e;
}
void Print(SqList *L)
{
int i;
if ((*L).elem == NULL) exit(1);
for ( i = 0; i < (*L).length; i++)
{
printf("%d ",(*L).elem[i]);
}
printf("\n");
}