顺序表是线性表的一种,本质而言是一个动态的一维数组,我用的不多,或许没接触到用的地方吧。
一个简单的实现代码如下:
- #include <stdio.h>
- #include <stdlib.h>
- #define LIST_SIZE 10/* the init allocate of list */
- #define LISTINCREMENT 10/* the increment allocate of list */
- #define Type int/* the element type*/
- #define bool int
- #define true 1
- #define false 0
- struct seq_list {
- Type *base_addr;/* the base address of seq list */
- int length;/* the current length of seq list */
- int list_size;/* the capacity of seq list*/
- };
- bool init_list(struct seq_list *sl)
- {
- sl->base_addr = (Type *)malloc(LIST_SIZE * sizeof(Type));
- if (sl->base_addr == NULL){
- printf("Error: malloc failed!");
- exit(-1);
- }
- sl->length = 0;
- sl->list_size = LIST_SIZE;
- return true;
- }
- /* insert e into sl before ith pos */
- bool insert_list(struct seq_list *sl, int i, Type e)
- {
- if (i < 0 || i > sl->length) {
- printf("Error: i is larger than length");
- return false;
- }
- if (sl->length >= sl->list_size) {
- Type *newbase_addr = (Type *)realloc(sl->base_addr, (sl->list_size + LISTINCREMENT) * sizeof(Type));
- if (newbase_addr == NULL)
- exit(-1);
- sl->base_addr = newbase_addr;
- sl->list_size += LISTINCREMENT;
- }
- Type *p;
- for (p = sl->base_addr + sl->length - 1; p >= sl->base_addr + i; p--)
- *(p + 1) = *p;
- *(p + 1) = e;
- ++sl->length;
- return true;
- }
- /* delete the ith pos element in list */
- bool delete_list(struct seq_list *sl, int i)
- {
- if (i < 0 || i > sl->length) {
- printf("Error: i is larger than length");
- return false;
- }
- Type *p;
- for ( p = sl->base_addr + i; p < sl->base_addr + sl->length - 1; p++)
- *p = *(p + 1);
- sl->length--;
- return true;
- }
- void destory_list(struct seq_list *sl)
- {
- free(sl->base_addr);
- sl->base_addr = NULL;
- sl->length = 0;
- sl->list_size = 0;
- }
- void display(struct seq_list *sl)
- {
- Type *p;
- for (p = sl->base_addr; p < sl->base_addr + sl->length; p++)
- printf("%d ", *p);
- }
- int main()
- {
- struct seq_list list;
- struct seq_list *plist = &list;
- int i;
- init_list(plist);
- for (i = 0; i < 10; i++)
- insert_list(plist, i, i);
- display(plist);
- delete_list(plist, 0);
- display(plist);
- destory_list(plist);
- return 0;
- }
这里 i 属于 [0, length)。merge_list用于合并两个已按非递减顺序排列的顺序表。
- void merge_list(struct seq_list *sl1, struct seq_list *sl2, struct seq_list *sl)
- {
- Type *p1, *p2, *p;
- int length;
- p1 = sl1->base_addr;
- p2 = sl2->base_addr;
- length = sl1->length + sl2->length;
- sl->base_addr = (Type *)malloc(length * sizeof(Type));
- p = sl->base_addr;
- if (sl->base_addr == NULL)
- exit(-1);
- while ((p1 < p1 + sl1->length) && (p2 < p2 + sl2->length)) {
- if (*p1 <= *p2)
- *p++ = *p1++;
- else
- *p++ = *p2++;
- }
- while (p1 < p1 + sl1->length)
- *p++ = *p1++;
- while (p2 < p2 + sl2->length)
- *p++ = *p2++;
- }