问题描述
- 顺序链表初始化错误,表的长度无法初始化
-
#include <stdio.h> #include <stdlib.> // squeue list operator #define MAXSIZE 100 typedef int Dataype; typedef struct { Dataype data[MAXSIZE]; int length; }Sqlist; // init a sqlist void Init_sqlist(Sqlist *list) { list = (Sqlist *)malloc(sizeof(Sqlist)); list->length = 10; if (NULL == list) { perror("Init_sqlist error"); exit(-1); } } // append element to sqlist void Append_sqlist(Sqlist *list,Dataype x) { printf("length %dn", list->length); if (MAXSIZE !=list->length) { list->data[list->length] = x; list->length++; } } // insert element into sqlist at index i void Insert_sqlist(Sqlist *list,int i,Dataype x) { int j; if (MAXSIZE == list->length) { printf("Sqlist fulln"); exit(-1); } if (i <0 || i > list->length) { printf("insert index errorn"); exit(-1); } for (j = list->length-1; j >= i-1; j--) { list->data[j+1] = list->data[j]; } list->data[i-1] = x; list->length = list->length +1; } // delete element which index i void Delete_sqlist(Sqlist *list,int i) { int j; if (i<0 || i>list->length) { printf("Delete_sqlist index erron"); exit(-1); } if (0==list->length) { printf("empty sqlistn"); exit(-1); } for (j = i-1; j < list->length; ++j) { list->data[j] = list->data[j+1]; } } // find element which x int Locate_sqlist(Sqlist *list,Dataype x) { int i; for (i = 0; i < list->length; ++i) { if (x == list->data[i]) { return i; } } return -1; } // print sqlist void Print_sqlist(Sqlist *list) { int i; if (0 != list->length) { for (i = 0; i < list->length; ++i) { printf("%d ", list->data[i]); } printf("n"); } else printf("emptyn"); } int main(int argc, char const *argv[]) { int i; Sqlist *list; Init_sqlist(list); for (i = 0; i < 10; ++i) { Append_sqlist(list,i); } Insert_sqlist(list,5,10); Print_sqlist(list); return 0; }
解决方案
void Init_sqlist(Sqlist *list)
->
void Init_sqlist(Sqlist *&list)
解决方案二:
还有少了一个.h
#include <stdlib.h>
结果
length 10
length 11
length 12
length 13
length 14
length 15
length 16
length 17
length 18
length 19
-842150451 -842150451 -842150451 -842150451 10 -842150451 -842150451 -842150451
-842150451 -842150451 -842150451 0 1 2 3 4 5 6 7 8 9
Press any key to continue . . .
解决方案三:
void Init__sqlist(Sqlist *&list),中 *&list = list 啊
时间: 2024-10-13 17:25:04