介绍
把所有的结点用一根线穿起来。
- 连续存储[数组]
- 离散存储[链表]
- 线性结构的两种常见的应用之一 栈
- 线性结构的两种常见的应用之二 队列(与时间相关的操作)
数组算法演示
#include <stdio.h> #include <malloc.h> #include <stdlib.h> #include <stdbool.h> struct Arr { int * pBase; int len; int cnt; }; void init_arr(struct Arr *, int); bool append_arr(struct Arr *, int); bool insert_arr(struct Arr *, int , int); bool delete_arr(struct Arr *, int, int *); bool is_empty(struct Arr *); bool is_full(struct Arr *); void sort_arr(struct Arr *); void show_arr(struct Arr *); void inversion_arr(struct Arr *); int main(void) { struct Arr arr; int val; init_arr(&arr, 6); show_arr(&arr); append_arr(&arr, 1); append_arr(&arr, -44); append_arr(&arr, 88); append_arr(&arr, 4); append_arr(&arr, 77); append_arr(&arr, 89); /*if (delete_arr(&arr, 5, &val)) { printf("delete success\n"); printf("delete element is :%d\n", val); } else { printf("delete error\n"); }*/ //append_arr(&arr, 6); //append_arr(&arr, 7); //insert_arr(&arr, , 99); /*if(append_arr(&arr, 8)) printf("add success\n"); else printf("add error\n");*/ show_arr(&arr); inversion_arr(&arr); show_arr(&arr); return 0; } void init_arr(struct Arr * pArr, int length) { pArr->pBase = (int *)malloc(sizeof(int) * length); if (NULL == pArr->pBase) { printf("DM error\n"); exit(-1); } else { pArr->len = length; pArr->cnt = 0; } return; } bool append_arr(struct Arr * pArr, int val) { if (is_full(pArr)) return false; pArr->pBase[pArr->cnt] = val; (pArr->cnt)++; return true; } bool insert_arr(struct Arr * pArr, int pos, int val) { int i; if (is_full(pArr)) return false; if (pos < 1 || pos > pArr->cnt+1) return false; for (i = pArr->cnt-1; i >= pos-1; --i) { pArr->pBase[i+1] = pArr->pBase[i]; } pArr->pBase[pos-1] = val; pArr->cnt++; return true; } bool delete_arr(struct Arr * pArr, int pos, int * pVal) { int i; if (is_empty(pArr)) return false; if (pos < 1 || pos >pArr->cnt) return false; *pVal = pArr->pBase[pos]; for (i = pos; i < pArr->cnt; ++i) { pArr->pBase[i-1] = pArr-> pBase[i]; } pArr->cnt--; return true; } bool is_empty(struct Arr * pArr) { if (0 == pArr->cnt) return true; else return false; } bool is_full(struct Arr * pArr) { if (pArr->cnt == pArr->len) return true; else return false; } void sort_arr(struct Arr * pArr) { int i; int j; for (i = 0; i < pArr->cnt; i++) { for (j = i; j < pArr->cnt; j++) { if (pArr->pBase[i] > pArr->pBase[j]) { int t; t = pArr->pBase[i]; pArr->pBase[i] = pArr->pBase[j]; pArr->pBase[j] = i; } } } } void show_arr(struct Arr * pArr) { if (is_empty(pArr)) printf("arr is Empty\n"); else { int i; for (i = 0; i < pArr->len; i++) printf("%d\n", pArr->pBase[i]); printf("\n"); } } void inversion_arr(struct Arr * pArr) { int i = 0; int j = pArr->cnt-1; int t; while (i < j) { t = pArr->pBase[i]; pArr->pBase[i] = pArr->pBase[j]; pArr->pBase[j] = t; ++i; --j; } return; }
时间: 2024-11-20 12:57:23