[領卓教育]順序連結串列(seqlist)的增刪改查與輸出
阿新 • • 發佈:2018-11-01
#include <stdio.h> #include <stdlib.h> #include <string.h> #define N 20 typedef struct { int data[N]; int last ;//記錄順序連結串列最後一個節點的位置(佇列的大小) }seqlist_t; /*****************建立一個空的順序連結串列********************/ seqlist_t * create_empty_seqlist(void) { seqlist_t * sl = (seqlist_t *)malloc(sizeof(seqlist_t)); memset(sl->data,0,N);//將所有成員清零 sl->last = -1; return sl ; } int insert_seqlist(seqlist_t * sl,int value) { sl->last ++ ; sl->data[sl->last % N] = value ; // 將陣列下標限制在0~(N-1) return 0 ; } int show_seqlist(seqlist_t * sl) { int i ; for(i=0;i<=sl->last;i++) { printf("%4d",sl->data[i]); } printf("\n"); return 0 ; } /********************刪除指定數*********************/ int remove_seqlist(seqlist_t * sl,int value) { int i , j ; for(i=0;i<=sl->last;i++) { if(sl->data[i] == value) { //將刪除節點之後的都前移 for(j=i;j<sl->last;j++) { sl->data[j] = sl->data[j+1] ; } sl->last -- ;//刪除一個數,連結串列長度會減一 } } return 0 ; } /********************改*********************/ int modify_seqlist(seqlist_t * sl,int old,int new) { int i ; for(i=0;i<=sl->last;i++) { if(sl->data[i] == old) { sl->data[i] = new ; } } return 0 ; } /********************查*********************/ int search_seqlist(seqlist_t * sl,int value) { int i ; for(i=0;i<=sl->last;i++) { if(sl->data[i] == value) { return 1 ; } } return 0 ; } int main(int argc, const char *argv[]) { seqlist_t * SL = create_empty_seqlist(); int i ; for(i=0;i<N;i++) { insert_seqlist(SL,i+1); } show_seqlist(SL); remove_seqlist(SL,5);//刪掉聊表中數字5 show_seqlist(SL); modify_seqlist(SL,1,50);//修改連結串列中國數字1為50 show_seqlist(SL); if(search_seqlist(SL,5)) { printf("5 is found \n"); } else { printf("5 is not found \n"); } if(search_seqlist(SL,6)) { printf("6 is found \n"); } else { printf("6 is not found \n"); } return 0; }