- Method 1:
- In the sequence table
末端插入
data element, the code is as follows: - Sample code:
int insert_seq_list_1(list_t *seq_list,int data){
if(NULL == seq_list){
printf("入参为NULL\n");
return -1;
}
if(N == seq_list->count){
printf("顺序表已满,插入失败\n");
return -1;
}
seq_list->a[seq_list->count].num = data;
seq_list->count++;
return 0;
}
-
Precautions:
-
1. After the formal parameter is passed to the function with the function of inserting data elements, it needs to be done
入参合理性检查
; -
2. Still need to judge at this time
顺序表所存储的数据元素是否已满
; -
3. In this sample code
count是计数的变量
,每次插入一个数据元素后,需要加1
, here易忽略
; -
Method 2:
-
In
任意位置插入
the data element of the sequence table, the code is as follows: -
Sample code:
int insert_seq_list_2(list_t *seq_list,int pos, int data){
if(NULL == seq_list){
printf("入参为NULL\n");
return -1;
}
if(N == seq_list->count){
printf("顺序表已满,插入失败\n");
return -1;
}
if( pos < 0 || pos > seq_list->count){
printf("插入位置不合理,插入失败\n");
return -1;
}
int i = 0;
i = seq_list->count-1;
while(i >= pos){
seq_list->a[i+1] = seq_list->a[i];
i--;
}
seq_list->a[pos].num = data;
seq_list->count++;
return 0;
}
- Precautions:
- 1. Same as method 1: After the formal parameter is passed to the function with the function of inserting data elements, it needs to be done
入参合理性检查
; - 2. Same as method 1: still need to judge at this time
顺序表所存储的数据元素是否已满
; - 3. Determine the data element to be inserted
位置在顺序表中是否合理
; - 4.
while循环或者for循环
After finding the position of the data element to be inserted, the data element at this position and all data elements after this position, the依次向后挪动一个位置
purpose is腾出所指定的待插入位置
; - 5. Assign the value of the data element to be inserted to the value of the position, that is, cover
记得count加1
;