DataStructure-用數組實現List

來源:互聯網
上載者:User

表的基本概念
表(線性表),是一種非常靈活的結構,可以根據自己的需要改變表的長度,也可以在其中任何位置對元素進行訪問、插入、刪除等操作。另外還可以將多個表串連成一個表,或者把一個表拆分多個表。

表的圖示結構

用數組實現表

#include <stdio.h>#include <malloc.h>typedef  int ListItem;//將int類型取別名為ListItem,讓代碼便於讀typedef struct alist *List;typedef struct alist{    int n;//表的長度    int maxsize;//表的最大長度    ListItem *table;//表元素數組}Alist;List ListInit(int size){//初始化List,參數為表長度    List L=malloc(sizeof *L);    L->table=malloc(size*sizeof(ListItem));//分配記憶體    L->maxsize=size;    L->n=0;    return L;}int ListEmpty(List L){//判斷表是否為空白    return L->n==0;}int ListLength(List L){//返回當前表長度    return L->n;}int ListLocate(ListItem x,List L){//返回元素x在表中的位置    int i;    for(i=0;i<L->n;i++){        if(L->table[i]==x) return ++i;    }    return 0;}int ListRetrieve(int k,List  L){//返回表L中k處的元素    if(k<1 || k>L->n) printf("out of bounds");    return L->table[k-1];}void ListInsert(int k,ListItem x,List L){//插入函數,將元素x插入位置k處,k+1之後位置的元素向右移    int i;    if(k<0 || k>L->n+1) {        printf("out of bounds!");    }    if(L->n==L->maxsize) printf("out of memory!");    for(i=L->n-1;i>=k;i++){        L->table[i+1]=L->table[i];    }    L->table[k-1]=x;    L->n++;}ListItem ListDelete(int k,List L){//刪除位元置K處的元素,將K+1之後的向左移    int i;    ListItem x;    if(k<1||k>L->n) printf("out of bounds!");    x=L->table[k-1];    for(i=k;i<L->n;i++) L->table[i-1]=L->table[i];    L->n--;             return x;}void printList(List L){//遍曆列表L,列印              int i;     for(i=0;i<L->n;i++){        printf("%d\n",L->table[i] );     }}void main(){    List  L=ListInit(10);    ListInsert(1,1,L);    ListInsert(2,2,L);    ListInsert(3,3,L);    ListInsert(4,4,L);    ListInsert(5,5,L);    ListInsert(6,6,L);    ListInsert(7,7,L);    ListDelete(3,L);    printList(L);    printf("element %d -> %d\n",5,ListLocate(5,L) );    printf("locate %d -> %d\n",5,ListRetrieve(5,L) );    printf("ListLength ->%d\n",ListLength(L) );}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.