From: 何. <sun...@gm...> - 2008-04-14 03:16:33
|
Hi everybody, I hava write a half of a Link list, but when i test some function of it, I find some problems that i don't know why, can anybody show me why will be the result like this? Here is the program in c++, thank you very much! > #include <iostream> > using namespace std; > > #define TRUE 1 > #define FALSE 0 > #define OK 1 > #define ERROR 0 > #define INFEASIBLE -1 > #define OVERFLOW -2 > > #define LIST_INIT_SIZE 100 > #define LISTINCREMENT 10 > > typedef int ElemType; > typedef int Status; > > typedef struct{ > ElemType *Elem; > int length; > int listsize; > }SqList; > > Status InitList_Sq(SqList &L){ > //构造一个空的线性表L; > L.Elem = (ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType)); > if(!L.Elem) exit(OVERFLOW); > L.length = 0; > L.listsize = LIST_INIT_SIZE; > return OK; > }//InitList_Sq > > Status ListInsert_Sq(SqList &L, int i, ElemType e){ > //在顺序线性表L中第i个位置之前插入新的元素e, > //Insert element e into the List L in position i > //i的合法值为 1 <= i <= ListLength_Sq(L)+1 > int * q, * p; > ElemType * newbase; > if(i < 1 || i > L.length+1) return ERROR; > if(L.length >= L.listsize){ > newbase = (ElemType *)realloc(L.Elem, (L.listsize + > LISTINCREMENT)*sizeof(ElemType)); > if(!newbase) exit(OVERFLOW); > L.Elem = newbase; > L.listsize += LISTINCREMENT; > } > q = &(L.Elem[i-1]); > for(p = &(L.Elem[L.length - 1]); p >= q; --p) *(p+1) = *p; > *q = e; > ++L.length; > return OK; > } > > Status ListDelete_Sq(SqList &L, int i, ElemType &e){ > //删除链表中的第i个元素, 用e返回其值 > //Delete from List L in position i, return its value with e > if(i < 1 || i >L.listsize) return ERROR; > int * p = &(L.Elem[i-1]); > e = *p; > ElemType *q = L.Elem + L.length - 1; > for(++p; p <= q; ++p) *(p-1) = *p; > --L.length; > return OK; > } > > Status ListShow(SqList &L){ > //显示顺序链表L的每个元素 > //Show the element of List L > int *p = &(L.Elem[L.length - 1]), *q = &(L.Elem[0]); > printf("The Element of List is:\n"); > for( ; q <= p; ++q) > printf("%d ", L.Elem[*(q)-1]); > printf("\n\n"); > return OK; > } > > int main() > { > SqList L1; > InitList_Sq(L1); > SqList L2; > InitList_Sq(L2); > int i, j; > for(i = 1; i <= 10; ++i) > ListInsert_Sq(L1, i, i); > for(j=1; j <= 5; ++j){ > i = 6; > ElemType e; > ListDelete_Sq(L1, i, e); > ListInsert_Sq(L2, j, e); > } > ListShow(L1); > ListShow(L2); > return 0; > } > I will be waiting here for you help, thank you! |