資料結構課後習題答案_基礎題1
阿新 • • 發佈:2018-11-12
#include<stdio.h> #include<stdlib.h> struct LinearList { int *list; int size; int MaxSize; }; typedef struct LinearList LIST; void InitList(LIST *L,int ms) { if((L->list=(int *)malloc(ms* sizeof(int)))==NULL){ printf("記憶體申請錯誤!\n"); exit(1); } L->size=0; L->MaxSize=ms; } int InsertList(LIST *L,int item,int rc) { int i; if(L->size>=L->MaxSize) return -1; if(rc<0) rc=0; if(rc>L->size) rc=L->size; for(i=L->size-1;i>=rc;i--) L->list[i+1]=L->list[i]; L->list[rc]=item; L->size++; return 0; } void OutputList(LIST *L) { int i; for(i=0;i<L->size;i++) printf("%d",L->list[i]); printf("\n"); } int FindList(LIST *L,int item) { int i; for(i=0;i<L->size;i++) if(item==L->list[i]); return i; return -1; } int DeleteList(LIST *L,int item) { int i,n; for(i=0;i<L->size;i++) if(item==L->list[i]) break; if(i<L->size) { for(n=i;n<L->size-1;n++) L->list[n]=L->list[n+1]; L->size--; return i; } return -1; } int DeleteList2(LIST *L,int rc) { int i,n; if(rc<0||rc>=L->size) return 1; for(n=rc;n<L->size-1;n++) L->list[n]=L->list[n+1]; L->size--; return 0; } int main() { LIST LL; int i,r; printf("沒有初始化情況:list addr=%p\tsize=%d\tMaxSize=%d\n",LL.list,LL.size,LL.MaxSize); InitList(&LL,100); printf("初始化後的情況:list addr=%p\tsize=%d\tMaxSize=%d\n",LL.list,LL.size,LL.MaxSize); while(1) { printf("請輸入元素值,輸入0結束插入操作:"); fflush(stdin); /*清空標準輸入緩衝區*/ scanf("%d",&i); if(i==0) break; printf("請輸入插入位置:"); scanf("%d",&r); InsertList(&LL,i,r-1); printf("線性表為: "); OutputList(&LL); } while (1) { printf("請輸入查詢元素值,輸入0結束查詢操作"); fflush(stdin); //清空標準輸入緩衝區 scanf("%d",&i); if(i==0) break; r=FindList(&LL,i); if(r<0) printf("沒找到\n"); else printf("有符合條件的元素,位置為: %d\n",r+1); } while(1) { printf("請輸入查詢元素值,輸入0結束查詢操作"); fflush(stdin); //清空標準輸入緩衝區 scanf("%d",&i); if(i==0) break; r=DeleteList(&LL,i); if(r<0) printf("沒找到\n"); else printf("有符合條件的元素,位置為: %d\n",r+1); OutputList(&LL); } while(1) { printf("請輸入查詢元素值,輸入0結束查詢操作"); fflush(stdin); //清空標準輸入緩衝區 scanf("%d",&i); if(i==0) break; r=DeleteList||(&LL,r-1); if(r<0) printf("位置越界\n"); else { printf("線性表為:"); OutputList(&LL); } } }