Data structure 4

Get element operation

Realize the specific operation of GetElem, which is to return the element value of the i-th position in the linear table L . (We only need to return the value of the i-1th subscript of the array)

#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0

typedef int Status;

//Status is the type of the function, and its value is the function result status code, such as OK, etc.
//Initial conditions, Sequence table L already exists, i <= i <= ListLength(L)
//Operation result, use e to return the i-th value in L

Status GetElem(SqList l, int i , ElemType *e)
{
if(L.length == 0 || i <1 || i> L.length)
{
return ERROR;
}
*e = L.data[i-1];

return OK;
}

Insert operation

Implement ListInsert(*L, i, e), that is, insert a new element e at the position of the i-th element in the linear list L.

Thinking:

  • If the insertion position is not reasonable, throw an exception
  • If the length of the linear table is greater than or equal to the array Length, throw an exception or dynamically increase the capacity of the array
  • Starting from the last y element, traverse forward to the i-th position m, and move them all backward by one position respectively
  • Fill the element to be inserted into position i
  • Linear table length j+1

//Initial condition, sequence table L already exists, i <= i <= ListLength(L)
//Operation result, insert a new element e at the position of the i-th element in L, the length of L+1

Status ListInsert(Sqlist *L, int i, ElemType e)< br />{
int k;

if(L->Length == MAXSIZE) //The sequence table is full
{
return ERROR;
}
if(i <1 || i> L->Length+1) //When i is not in the range
{
return ERROR;
}
if(i <= L->Length) //The inserted data is not at the end of the table
{
for(k = L->Length-1; k >= i-1; k-- )
{
L->data[k+1] = L->data[k];
}
}
L->data[i-1 ] = e; //If you insert directly at the end of the table
L->Length++;

return OK;
}

Leave a Comment

Your email address will not be published.