#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <Windows.h>
#define MAXSIZE 40
//顺序表结构体
typedef struct
{
int data[MAXSIZE]; //存放数据的数组
int size; //顺序表的当前长度
}SeqList;
//初始化
void init_SeqList(SeqList* list)
{
for (int i = 0; i < MAXSIZE; i++)
{
list->data[i] = 0;
}
list->size = 0;
}
//创建顺序表
void create_SeqList(SeqList* list)
{
int len;
printf("请输入要创建的顺序表的长度:");
scanf_s("%d", &len);
printf("请输入数据到顺序表:\n");
for (int i = 0; i < len; i++)
{
scanf_s("%d", &list->data[i]);
list->size++;
}
}
//冒泡排序
void bubbleSort_SeqList(SeqList* list)
{
for (int i = 0; i < list->size - 1; i++)
{
for (int j = 0; j < list->size - 1 - i; j++)
{
if (list->data[j] > list->data[j + 1])
{
int temp = list->data[j];
list->data[j] = list->data[j + 1];
list->data[j + 1] = temp;
}
}
}
}
//从顺序表中删除给定区间内的所有数据
void deleteValueFromSeqList(SeqList* list)
{
int s, t, i, j, num = 0;
printf("请输入要删除的区间值:");
scanf_s("%d%d", &s, &t);
if (list->size == 0)
{
printf("顺序表为空不能删除!\n");
}
if (s >= t)
{
printf("输入的区间范围不合理!\n");
}
for (i = 0; list->data[i] < s; i++);//找到第一个大于s的值,位置记录在i中
for (j = i; list->data[j] <= t; j++);//找到第一个大于t的值,位置记录在j中
num = j - i;//删除的元素个数
for (int k = j; k < list->size; k++,i++)//将t之后的元素进行前移
{
list->data[i] = list->data[k];
}
list->size = list->size - num;
}
//打印
void printf_SeqList(SeqList* list)
{
for (int i = 0; i < list->size; i++)
{
printf("%d ", list->data[i]);
}
printf("\n");
}
int main(void)
{
SeqList list;
init_SeqList(&list);
create_SeqList(&list);
printf("初始顺序表为:\n");
printf_SeqList(&list);
bubbleSort_SeqList(&list);
printf("排序后的顺序表为:\n");
printf_SeqList(&list);
deleteValueFromSeqList(&list);
printf("删除给定区间的数据后的顺序表为:\n");
printf_SeqList(&list);
system("pause");
return EXIT_SUCCESS;
}
王道数据结构顺序表算法题第四题
最新推荐文章于 2024-08-19 13:32:52 发布