C language linear table sequence storage structure example details
- 2020-05-26 09:42:31
- OfStack
C language linear table sequence storage structure example details
1. What is a sequential storage structure?
The data elements of a linear table are stored in sequence in a 1-segment contiguous location.
2. Sequential storage structure of linear table
#include<stdio.h>
#include<stdlib.h>
#define Max 80 // Initial allocation of storage space
#define Increment 10 // Storage space allocation increment
typedef struct
{
int *elem; // Storage space base address, here is int Type b, it depends
int length; // Element table current length
int size; // The memory capacity allocated when the parent
}SqList;
3. The initialization operation of the sequence table is to allocate a predetermined array space for the sequence table, and set the length of the sequence table to 0.
<1>int InitList(SqList &L)
{
L.elem=(int *)malloc(Max*sizeof(int));
if(!L.elem)
return;//exit(0); // Memory allocation failed
L.length=0; // The length of the empty table is zero 0
L.size=Max; // Initial storage capacity
return Ok;
}
<2>int CreatList(SqList &L)
{
L.elem=(int *)malloc(Max*sizeof(int));
if(!L.emle)
return;//exit(0);
L.length=0;
L.size=Max;
printf(" Please enter the length of the table :");
scanf("%d",&L.length);
printf(" Please enter the %d The number of :",L.length);
for(i=0;i<L.length;i++)
scanf("%d",&L.elem[i]);
}
4. Get element operation: return the position of the element value of the i position in the linear table
int GetElem(SqList &L,int i,int e)
{
// 1 <= i <= L.length
if( i <1 || i > L.length)
return ERROR;
*e=L.elem[i-1];
return Ok;
}
5 linear table insert operation
"
int Insert(SqList &L)
{
int *_new;
int i;
int e;
printf( "Enter the location to insert and its elements:" );
scanf( " %d %d " ,&i,&e);
if(i<1||i>L.length)
{
printf( "The insertion position is illegal!" );
return ERROR;
}
if(L.length>=L.size) // Current space is full, increase allocation
{
_new=(int)malloc(L.elem,(L.length+Increment)*sizeof(int));
if(!_new) // Memory allocation failed
return; //exit(0);
L.elem=_new; // The new base address
L.size=L.size+Increment; // Increase storage capacity
}
q=&(L.elem[i-1]); //q Is the insertion position
for(p=&(L.elem(L.length-1));p>=q; � p) // Move the element to the right after insertion
*q=e; // insert e
++L.length; // The length of the add 1
return OK;
}
6. Delete element ' ' '
int ListDelete(SqList &L,int i,int *e)
{
int k;
if(L.length==0) // The linear table is empty
return ERROR;
if(i<1||i>L.length) // Incorrect insertion
return ERROR;
*e=L.elem[i-1];
if(i<L.length) // If the insertion is not the last position
{
for(k=i;k<L.length;k++)
L.elem[k-1]=L.elem[k];
}
L.length--
return OK;
}
Thank you for reading, I hope to help you, thank you for your support of this site!