class-notes/2207/线性结构.md
2025-02-06 22:43:19 +08:00

157 lines
3.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

### 顺序表
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <math.h>
#include <Windows.h>
/*
顺序表 连续存储的动态数组
链表 分散存储的动态数组
栈 后进先出的数组
队列 先进先出的数组
*/
//顺序表
typedef struct List{
int *arr;//用来存储数据首地址
int size;//用来存储当前已经插入的元素个数
int capacity;//用来存储最大的容量
}List;
//函数声明
//对顺序表进行初始化
void init(List *list, int n){
//对List结构体中arr指针变量 指向一块动态内存分配的地址
list->arr = (int *)malloc(sizeof(int)*n);
//malloc 用来分配指定大小的内存空间并返回 void*类型的首地址
list->size = 0;//设置当前元素个数为0
list->capacity = n;//设置当前数组容量为n
memset(list->arr, 0, sizeof(int)*n);
//memset对指定内存空间 设置初始值为0
}
//传入list结构体指针 并对其中
void enlargeList(List *list){
//对数组元素进行扩容 数组起始地址 扩大后的内存大小
list->arr = (int *)realloc(list->arr, sizeof(int)*list->capacity*2);
//对扩容后的空间进行初始化赋值给0
memset(list->arr + list->capacity, 0, list->capacity*sizeof(int));
//容量扩大一倍
list->capacity *= 2;
}
//在顺序表最后面插值
void add(List *list, int num){
//对数组最后一个位置进行赋值
//当前数组元素个数应小于当前容量
if(list->size == list->capacity){
enlargeList(list);
}
*(list->arr + list->size) = num;
list->size++;//元素个数加一
}
//遍历数组中元素并打印
void traverse(List *list){
int i;
for(i=0;i<list->size;i++){
printf("%2d ", *(list->arr + i));
if((i+1)%10==0){
printf("\n",(i+1));
//Sleep(1000);
}
}
printf("\n");
}
int getRandNum(int startNum, int endNum){
return rand()%(endNum - startNum) + startNum;
//计算出start~end之间的随机整数并包括start和end
}
//在指定位置插值
void addByIndex(List *list, int num, int n){
int i;
if(list->size == list->capacity){
enlargeList(list);
}
//将这个位置-1开始的所有元素整体往后挪动一个位置
for(i=list->size-1;i>=n-1;i--){
*(list->arr+i+1) = *(list->arr+i);
}
*(list->arr+n-1) = num;
list->size++;//元素个数+1
}
//删除指定位置元素并返回该元素
int deleteByIndex(List *list, int n){
int i;
//从删除位置n-1开始 元素整体前移覆盖掉n-1位置需要删除的元素
for(i=n-1;i<list->size-1;i++){
*(list->arr + i) = *(list->arr + i + 1);
}
*(list->arr + list->size - 1) = 0;
list->size--;
}
//判断顺序表是否为空
//size为0则返回1 代表数组是空的
int isEmpty(List *list){
return list->size?0:1;
}
//判断顺序表是否已满
//size==capacity 为真
int isFull(List *list){
return list->size == list->capacity?1:0;
}
//获取顺序表中的元素个数
int size(List *list){
return list->size;
}
//对顺序表中元素进行升序排序
void sort(List *list){
int i, j, temp;
for(i=0;i<list->size-1;i++){
for(j=0;j<list->size-1-i;j++){
if(list->arr[j] > list->arr[j+1]){
temp = list->arr[j];
list->arr[j] = list->arr[j+1];
list->arr[j+1] = temp;
}
}
}
}
int main(void){
List list;//定义结构体变量
List *p = &list;
int i;
system("color f4");
srand((unsigned)time(NULL));//以当前时间为随机数种子
init(p, 1);//顺序表的初始化
add(p, 1);
add(p, 2);
add(p, 3);
addByIndex(p, 66, 2);
addByIndex(p, 100, 1);
deleteByIndex(p, 3);
sort(p);
traverse(p);
return 0;
}
```