C language creates a sequence table and inserts element detailed comments

A sequence table is a data structure in which data elements are sequentially stored in a group of storage units with consecutive addresses. A sequential list is a type of linear list. A linear list is the most common and simplest data structure. A linear list is a finite sequence of n data elements. We use c language to create sequence table and insert elements.

IDE : Code::Blocks 17.12

Compiler : GNU GCC Compiler

/* create a sequence table and insert elements */
#include <stdio.h>
#include <stdlib.h>
#define Listsize 100 //The sequence table can accommodate the maximum value

//Declaration order table
typedef struct sqlist{
    int data[Listsize]; // elements in the storage order list
    int length; //Number of elements in the sequence table
};

//Insert an element in the sequence table
void InsertList(struct sqlist * list,int t,int i){ //The insertion position is i, and the insertion value is t
    int j;
    if(i<0 || i>list->length){ //Invalid insertion position
        printf("Position error!");
        exit(1);
    }
    if(list->length>=Listsize){ //Exceed the range of the sequence table, overflow
        printf("overflow");
        exit(1);
    }
    for(j=list->length-1;j>=i;--j){ //Free up position i for inserting data t
        list->data[j+1]=list->data[j];
    }
    list->data[i]=t; //Insert data t at position i
    list->length++; //Add 1 to the length of the sequence table
}

intmain()
{
    struct sqlist * sq; //Create a sequence table sq
    int i,n,t;
    sq=(struct sqlist *)malloc(sizeof(struct sqlist)); //Allocate space
    sq->length=0; //The length of the initialization sequence table is 0
    printf("The size of the input sequence table: ");
    scanf("%d",&n);
    printf("Please enter the elements of the sequence table:\n"); //Insert n elements in the sequence table
    for(i=0;i<n;++i){
        scanf("%d",&t);
        InsertList(sq,t,i); //The insertion position is i and the value is t
    }
    printf("This chain is now:\n");
    for(i=0;i<sq->length;++i){ //Output the contents of the sequence table
        printf("%d ",sq->data[i]);
    }
    return 0;
}


------Be smarter than others, work harder than others------

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324718287&siteId=291194637