C language: sequence table

Sequence table

1. Representation of sequential storage structure

typedef MAXSIZE 100
typedef int  ElemType
typedef struct{
    
    
	ElemType elem[MAXSIZE];
	int last;//线性表中最后一个元素在数组中的位置(下标值),空表置为-1
}Seqlist;

Sequence table length (last element sequence number): L.last+1
sequence number in the sequence table is iii elementai a_iai: L.elem[i-1]
position (subscript iiI )0. 6. 5. 4. 3. 1 2
Reference (firstiii )1 2 3 4 5 6 7

2. Search by content operation

int Locate(SeqList L, ElemType e)
{
    
    
	i = 0;
	while((i <= L.last) && (L.elem[i] != e))
	i++;
	if(i <= L.last) return i+1;
	else return -1;
}

The time complexity is O (n) O(n)O ( n )

Three. Insert operation

int InsList(SeqList *L, int i, ElemType e)
{
    
    
//在第i个元素之前插入元素e,i的合法范围为1≤i≤L->last+2
	if(i < 1 || i > L->last + 2)
	{
    
    
		printf("插入值不合法");
		return 0;
	}
	if(L->last >= MAXSIZE - 1)
	{
    
    
		printf("表已满,无法插入");
		return 0;
	}
	for(int j = L->last;j >= i - 1;j--)
	 L->elem[j+1] = L->elem[j];
	 L->elem[i-1] = e;//或L->elem[j+1] = e;
	 L->last++;//相当于(L->last)++,运算顺序从左至右
	 return 1;
}

3. Delete operation

int DelList(SeqList *L, int i, ElemType *e)
{
    
    
//删除第i个元素,并用指针参数e返回其值,i的合法范围1≤i≤L->last+1
	if(i < 1 || i > L->last+1)
	{
    
    
		printf("删除位置不合法");
		return 0;
	}
	//将删除的元素存放在e所指向的变量中
	*e = L->elem[i-1];
	//将后面的元素向前移动
	for(int j = i;j <= L->last;j++)
	L->elem[j-1] = L->elem[j];
	L->last--;
	return 1;
}

Four. Merge operation

  There are two sequence tables, LA and LB, whose elements are all arranged in increasing order. Please merge them into a sequence table LC, which requires that LC is also arranged in increasing order.
For example: LA = (2, 2, 3) LB = (1, 3, 3, 4)
then LC = (1, 2, 2, 3, 3, 4)

void MergeList(Seqlist *LA, Seqlist *LB, Seqlist *LC)
{
    
    
	int i = 0, j = 0, k = 0;
	while(i <= LA->last && j <= LB->last)
	if(LA->elem[i] <= LB->elem[j])
		LC->elem[k++] = LA->elem[i++];
	else LC->elem[k++] = LB->elem[j++];
	//当LA有余下元素时,将LA余下元素赋给LC
	while(i <= LA->last)
	LC->elem[k++] = LB->elem[i++];
	//当LB有余下元素时,将LB余下元素赋给LC
	while(j <= LB->last)
	LC->elem[k++] = LB->elem[j++];
	
	LC->last = LA->last + LB->last + 1;
}

Guess you like

Origin blog.csdn.net/m0_51354361/article/details/114850303