Initial commit

This commit is contained in:
xixu-me committed 2024-03-17 22:30:49 +08:00
commit bdf71aef37
120 files changed
+8284

No files matched your search

+128
View File
@@ -0,0 +1,128 @@
// 预编译命令
#include <stdio.h>
#include <stdlib.h>
// 数据结构定义
typedef struct
{
int num;
char name[20];
int score[3];
int ave;
} Student; // 结构体类型定义
// 函数声明
int menu_select();
void input(Student s[5]);
void output(Student s[5], int n);
void average(Student s[5]);
void sort(Student s[5]);
// 主函数
int main() {
Student stu[5]; // 准备实参
for (;;) {
switch (menu_select()) {
case 1:
printf("请输入5位同学的信息\n");
input(stu); // 函数调用
break;
case 2:
printf("输出5位同学的信息\n");
output(stu, 5);
break;
case 3:
average(stu);
printf("平均分已经求过\n");
break;
case 4:
sort(stu);
printf("按照平均分由高到低排序已经完成\n");
break;
case 5:
printf("输出前3名同学的信息\n");
sort(stu); // 输出前3名之前先排序
output(stu, 3);
break;
case 0:
printf("谢谢使用本软件\n");
exit(0);
}
}
return 0;
}
// 菜单函数
int menu_select() {
int sn;
printf("\n1.输入5位同学的信息\n");
printf("2.输出5位同学的信息\n");
printf("3.求平均分\n");
printf("4.排序\n");
printf("5.输出前三名\n");
printf("0.结束\n");
printf("Input 0~5:");
for (;;) {
scanf("%d", &sn);
if (sn < 0 || sn > 5)
printf("\n输入错误,重选0~5:");
else
break;
}
return sn;
}
// 输入函数
void input(Student s[5]) {
int i, j;
for (i = 0; i < 5; i++) {
scanf("%d", &s[i].num);
scanf("%s", s[i].name);
for (j = 0; j < 3; j++) {
scanf("%d", &s[i].score[j]);
}
}
}
// 输出函数
void output(Student s[5], int n) // 增加一个参数n,为输出元素的个数
{
int i, j;
for (i = 0; i < n; i++) {
printf("%d\t", s[i].num);
printf("%s\t", s[i].name);
for (j = 0; j < 3; j++) {
printf("%d\t", s[i].score[j]);
}
printf("%d\t", s[i].ave);
printf("\n");
}
}
// 求平均分
void average(Student s[5]) {
int i, j, sum;
for (i = 0; i < 5; i++) {
sum = 0;
for (j = 0; j < 3; j++) {
sum += s[i].score[j];
}
s[i].ave = sum / 3;
}
}
// 冒泡排序
void sort(Student s[5]) {
average(s); // 排序之前应该先求过平均分
int i, j;
Student t;
for (i = 4; i > 0; i--) {
for (j = 0; j < i; j++) {
if (s[j].ave < s[j + 1].ave) {
t = s[j];
s[j] = s[j + 1];
s[j + 1] = t;
}
}
}
}
@@ -0,0 +1,5 @@
111 aaa 88 88 88
222 bbb 66 66 66
333 ccc 99 99 99
444 ddd 55 55 55
555 fff 77 77 77
+206
View File
@@ -0,0 +1,206 @@
// 预编译命令
#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define LIST_INIT_SIZE 10 // 表存储空间的初始分配量
#define LISTINCREMENT 2 // 线性表存储空间的分配增量
// 数据结构
typedef int Status;
typedef int ElemType;
typedef struct
{
ElemType *elem; // 存储空间基址
int length; // 当前长度
int listsize; // 当前分配的存储容量(以sizeof(ElemType)为单位)
} SqList;
// 函数声明
int menu_select();
Status InitList_Sq(SqList &L);
Status CreatList_Sq(SqList &L, int n);
void PrintList_Sq(SqList L);
Status ListInsert_Sq(SqList &L, int i, ElemType e);
Status ListDelete_Sq(SqList &L, int i, ElemType &e);
int LocateElem_Sq(SqList L, ElemType e, Status (*compare)(ElemType, ElemType));
Status equal(ElemType x, ElemType y);
// 主函数
int main() {
SqList L;
Status s;
int n, i, e;
for (;;) {
switch (menu_select()) {
case 1:
s = InitList_Sq(L);
if (s)
printf("初始化成功\n");
else
printf("初始化失败\n");
break;
case 2:
printf("输入线性表的长度:");
scanf("%d", &n);
s = CreatList_Sq(L, n);
if (s)
printf("创建成功\n");
else
printf("创建失败\n");
break;
case 3:
PrintList_Sq(L);
break;
case 4:
printf("请输入插入的位序:");
scanf("%d", &i);
printf("请输入插入的新元素的值:");
scanf("%d", &e);
s = ListInsert_Sq(L, i, e);
if (s)
printf("插入成功!\n");
else
printf("插入失败!\n");
break;
case 5:
printf("输入删除的位序:");
scanf("%d", &i);
s = ListDelete_Sq(L, i, e);
if (s)
printf("删除了元素%d成功\n", e);
else
printf("删除失败\n");
break;
break;
case 6:
printf("请输入查找的元素的值:");
scanf("%d", &e);
i = LocateElem_Sq(L, e, equal); // 指向函数类型的指针作形参,实参用同类型的函数名equal
if (i)
printf("%d的逻辑位序是%d\n", e, i);
else
printf("查找失败!\n");
break;
case 0:
printf("程序结束,谢谢使用!\n\n");
exit(0);
}
}
return 0;
}
// 菜单函数
int menu_select() {
int sn;
printf("\n显示菜单\n");
printf("1.初始化\n");
printf("2.创建\n");
printf("3.显示\n");
printf("4.插入\n");
printf("5.删除\n");
printf("6.查找\n");
printf("0.退出\n");
printf("输入 0-6:");
for (;;) {
scanf("%d", &sn);
if (sn < 0 || sn > 6)
printf("\n输入错误,重选0-6:");
else
break;
}
return sn;
}
// 初始化空的动态顺序表函数
Status InitList_Sq(SqList &L) {
L.elem = (ElemType *)malloc(LIST_INIT_SIZE * sizeof(ElemType));
if (!L.elem)
return (OVERFLOW);
L.length = 0;
L.listsize = LIST_INIT_SIZE;
return OK;
}
// 创建动态顺序表(输入n个元素)
Status CreatList_Sq(SqList &L, int n) {
int i;
if (n > L.listsize)
return (ERROR);
printf("输入%d个整型数:", n);
for (i = 1; i <= n; i++) {
scanf("%d", &L.elem[i - 1]); // 类C代码中无格式输入字符串,需要补充
}
L.length = n;
return OK;
}
// 输出顺序表元素
void PrintList_Sq(SqList L) {
int i;
for (i = 1; i <= L.length; i++) {
printf("%d\t", L.elem[i - 1]);
}
printf("\n");
}
// 插入新元素e到第i个位序
Status ListInsert_Sq(SqList &L, int i, ElemType e) {
ElemType *newbase, *q, *p; // 类C代码中不含变量定义,需要补充
if (i < 1 || i > L.length + 1) // 插入位置不合法
return ERROR;
if (L.length >= L.listsize) // 当前储存空间不足
{
newbase = (ElemType *)realloc(L.elem, (L.listsize + LISTINCREMENT) * sizeof(ElemType));
if (!newbase)
exit(OVERFLOW); // 存储位置失败
L.elem = newbase; // 新基址
L.listsize += LISTINCREMENT; // 增加存储位置
}
q = &(L.elem[i - 1]); // 要插入的位置
for (p = &(L.elem[L.length - 1]); p >= q; --p)
*(p + 1) = *p; // 插入位置之后的元素右移
*q = e; // 插入e
++L.length;
return OK; // 表长增加1
} // ListInsert_Sq
// 删除第i个元素
Status ListDelete_Sq(SqList &L, int i, ElemType &e) {
ElemType *p, *q; // 补出变量定义
if ((i < 1) || (i > L.length))
return ERROR;
p = &(L.elem[i - 1]);
e = *p;
q = L.elem + L.length - 1;
e = *p;
q = L.elem + L.length - 1;
for (++p; p <= q; ++p)
*(p - 1) = *p;
--L.length;
return OK;
}
// 查找给定值的位序
int LocateElem_Sq(SqList L, ElemType e, Status (*compare)(ElemType, ElemType) /*指向函数类型的指针作形参*/) {
ElemType *p;
int i; // 补出变量定义
i = 1; // 当前元素的逻辑位序
p = L.elem; // 当前元素的物理地址
while (i <= L.length && !(*compare)(*(p++), e))
++i;
if (i <= L.length)
return i;
else
return 0;
} // LocateElem_Sq
// 判断两个数据元素是否相等的函数
Status equal(ElemType x, ElemType y) // 为LocateElem_Sq函数准备第三个实参
{
if (x == y)
return OK;
else
return ERROR;
}
+247
View File
@@ -0,0 +1,247 @@
// 预编译命令
#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR 0
#define OVERFLOW -2
// 数据结构
typedef int Status;
typedef int ElemType;
typedef struct LNode
{
ElemType data;
struct LNode *next;
} LNode, *LinkList;
// 函数声明
int menu_select();
int menu_select();
void CreateList_L(LinkList &L, int n);
void PrintList_L(LinkList L);
Status GetElem_L(LinkList &L, int i, ElemType &e);
Status ListInsert_L(LinkList &L, int i, ElemType e);
Status ListDelete_L(LinkList &L, int i, ElemType &e);
int LocateElem_L(LinkList L, ElemType e);
// 主函数
int main()
{
LinkList L;
int n, i, e, k;
for (;;)
{
switch (menu_select())
{
case 1:
printf("请输入元素的个数:");
scanf("%d", &n);
CreateList_L(L, n);
printf("创建完成\n");
break;
case 2:
PrintList_L(L);
break;
case 3:
printf("请输入要查找的元素的位序:");
scanf("%d", &i);
if (GetElem_L(L, i, e) == OK) // 调用取元素函数,如果成功,返回元素值给 e
{
printf("第%d个元素的值是%d\n", i, e);
}
else // 如果失败,输出错误信息
{
printf("查找失败,不存在第%d个元素\n", i);
}
break;
case 4:
printf("请输入要插入的元素的位序和值,用空格隔开:");
scanf("%d %d", &i, &e);
if (ListInsert_L(L, i, e) == OK) // 调用插入函数,如果成功,输出插入成功信息
{
printf("插入成功\n");
}
else // 如果失败,输出错误信息
{
printf("插入失败,插入位置不合法\n");
}
break;
case 5:
printf("请输入要删除的元素的位序:");
scanf("%d", &i);
if (ListDelete_L(L, i, e) == OK) // 调用删除函数,如果成功,返回删除的元素值给 e,并输出删除成功信息
{
printf("删除成功,删除的元素值是%d\n", e);
}
else // 如果失败,输出错误信息
{
printf("删除失败,删除位置不合法\n");
}
break;
case 6:
printf("请输入要查找的元素的值:");
scanf("%d", &e);
k = LocateElem_L(L, e); // 调用查找函数(已知元素找位序),返回位序给 k
if (k != 0) // 如果 k 不为 0,说明找到了元素 e,并输出其位序
{
printf("找到了元素%d,它的位序是%d\n", e, k);
}
else // 如果 k 为 0,说明没有找到元素 e,并输出查找失败信息
{
printf("查找失败,不存在元素%d\n", e);
}
break;
case 0:
printf("程序结束,谢谢使用!\n\n");
exit(0);
}
}
return 0;
}
int menu_select()
{
int sn;
printf("\n显示菜单\n");
printf("1.创建\n");
printf("2.显示\n");
printf("3.取元素\n");
printf("4.插入\n");
printf("5.删除\n");
printf("6.查找\n");
printf("0.退出\n");
printf("输入 0-6:");
for (;;)
{
scanf("%d", &sn);
if (sn < 0 || sn > 6)
printf("\n输入错误,重选0-6:");
else
break;
}
return sn;
}
// 创建单链表,头插法,已知线性表的长度
void CreateList_L(LinkList &L, int n)
{
LinkList p;
int i;
L = (LinkList)malloc(sizeof(LNode));
L->next = NULL;
printf("请逆序输入%d个元素:\n", n);
for (i = n; i >= 1; i--)
{
p = (LinkList)malloc(sizeof(LNode));
scanf("%d", &p->data); // 格式输入字符串补出来
p->next = L->next;
L->next = p;
}
}
// 输出单链表
void PrintList_L(LinkList L)
{
LinkList p;
p = L->next;
printf("输出链表中的元素:\n");
while (p)
{
printf("%d\t", p->data);
p = p->next;
}
printf("\n");
}
// 取元素函数
Status GetElem_L(LinkList &L, int i, ElemType &e)
{
// 在单链表 L 中查找第 i 个元素,并将其值赋给 e
LinkList p; // 定义一个指针 p
int j; // 定义一个计数器 j
p = L->next; // 让 p 指向链表 L 的第一个结点
j = 1; // 初始化 j 为 1
while (p && j < i) // p 不为空且计数器 j 还没有等于 i 时,循环继续
{
p = p->next; // 让 p 指向下一个结点
j++; // 让 j 增加 1
}
if (!p || j > i) // 如果 p 为空或者 j 大于 i,说明第 i 个元素不存在
{
return ERROR; // 返回错误标志
}
e = p->data; // 取出第 i 个元素的数据,赋给 e
return OK; // 返回成功标志
}
// 插入函数
Status ListInsert_L(LinkList &L, int i, ElemType e)
{
// 在单链表 L 中的第 i 个位置插入新的元素 e
LinkList p, s; // 定义两个指针 p 和 s
int j; // 定义一个计数器 j
p = L; // 让 p 指向链表 L 的头结点
j = 0; // 初始化 j 为 0
while (p && j < i - 1) // 寻找第 i-1 个结点,p 指向该结点
{
p = p->next;
j++;
}
if (!p || j > i - 1) // 如果 p 为空或者 j 大于 i-1,说明插入位置不合法
{
return ERROR; // 返回错误标志
}
s = (LinkList)malloc(sizeof(LNode)); // 分配一个新的结点 s
s->data = e; // 将新元素 e 赋给 s 的数据域
s->next = p->next; // 将 s 的指针域指向 p 的后继结点
p->next = s; // 将 p 的指针域指向 s 结点
return OK; // 返回成功标志
}
// 删除函数
Status ListDelete_L(LinkList &L, int i, ElemType &e)
{
// 在单链表 L 中删除第 i 个元素,并用 e 返回其值
LinkList p, q; // 定义两个指针 p 和 q
int j; // 定义一个计数器 j
p = L; // 让 p 指向链表 L 的头结点
j = 0; // 初始化 j 为 0
while (p->next && j < i - 1) // 寻找第 i-1 个结点,p 指向该结点,且保证 p 的后继不为空(即第 i 个结点存在)
{
p = p->next;
j++;
}
if (!(p->next) || j > i - 1) // 如果 p 的后继为空或者 j 大于 i-1,说明删除位置不合法
{
return ERROR; // 返回错误标志
}
q = p->next; // 让 q 指向要删除的结点(即第 i 个结点)
p->next = q->next; // 将 q 的后继赋给 p 的后继(即相当于断开了 q 结点)
e = q->data; // 将 q 结点的数据赋给 e(用于返回)
free(q); // 释放 q 结点的空间
return OK; // 返回成功标志
}
// 查找函数(已知元素找位序)
int LocateElem_L(LinkList L, ElemType e)
{
LinkList p;
int i;
p = L->next;
i = 1;
while (p && p->data != e) // 从第一个结点开始,遍历链表,直到找到元素 e 或者链表结束
{
p = p->next;
i++;
}
if (p) // 如果找到了元素 e,返回其位序 i
{
return i;
}
else // 如果没有找到元素 e,返回 0
{
return 0;
}
}
+175
View File
@@ -0,0 +1,175 @@
// 预编译命令
#include <stdio.h>
#include <stdlib.h>
#include "stack.h"
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define STACK_INIT_SIZE 10 // 顺序栈存储空间的初始分配量
#define STACKINCREMENT 2 // 顺序栈存储空间的分配增量
// 输出顺序栈的元素
void PrintStack(SqStack S) {
SElemType *p;
for (p = S.base; p < S.top; p++) {
printf("%d\t", *p);
}
}
// 输入n个元素入栈
Status CreateStack(SqStack &S, int n) {
int i;
if (n > S.stacksize)
return (ERROR);
printf("输入%d个整型数:", n);
for (i = 1; i <= n; i++) {
scanf("%d", S.top++);
}
return OK;
}
// 菜单函数
int menu_select() {
int sn;
printf("\n显示菜单\n");
printf("1.初始化栈\n");
printf("2.创建栈\n");
printf("3.显示栈\n");
printf("4.取栈顶元素\n");
printf("5.入栈\n");
printf("6.出栈\n");
printf("7.判断栈空否\n");
printf("8.销毁栈\n");
printf("9.数制转换\n");
// printf("10.括号匹配\n");
printf("0.退出\n");
printf("输入 0-8:");
for (;;) {
scanf("%d", &sn);
if (sn < 0 || sn > 9)
printf("\n输入错误,重选0-8:");
else
break;
}
return sn;
}
void Conversion() {
SqStack S;
InitStack(S);
int N;
printf("输入要转换的十进制数:");
scanf("%d", &N);
while (N) {
Push(S, N % 8);
N /= 8;
}
printf("转换后的八进制数为:");
while (!StackEmpty(S)) {
int e;
Pop(S, e);
printf("%d", e);
}
printf("\n");
}
// void BracketMatch() {
// SqStack S;
// InitStack(S);
// char c;
// printf("输入括号序列:");
// while ((c = getchar()) != '\n') {
// if (c == '(')
// Push(S, c);
// else if (c == ')') {
// if (StackEmpty(S)) {
// printf("括号不匹配\n");
// return;
// }
// Pop(S, c);
// }
// }
// if (StackEmpty(S))
// printf("括号匹配\n");
// else
// printf("括号不匹配\n");
// }
// 主函数
int main() {
SqStack S;
Status s;
int n;
SElemType e;
for (;;) {
switch (menu_select()) {
case 1:
s = InitStack(S);
if (s)
printf("初始化成功\n");
else
printf("初始化失败\n");
break;
case 2:
printf("输入栈的长度:");
scanf("%d", &n);
s = CreateStack(S, n);
if (s)
printf("创建成功\n");
else
printf("创建失败\n");
break;
case 3:
PrintStack(S);
break;
case 4:
s = GetTop(S, e);
if (s)
printf("栈顶元素为%d\n", e);
else
printf("栈为空,取栈顶元素失败\n");
break;
case 5:
printf("输入入栈的元素值:");
scanf("%d", &e);
s = Push(S, e);
if (s)
printf("%d入栈成功\n", e);
else
printf("入栈失败\n");
break;
case 6:
s = Pop(S, e);
if (s)
printf("%d出栈成功\n", e);
else
printf("栈为空,出栈失败\n");
break;
case 7:
s = StackEmpty(S);
if (s)
printf("栈为空\n");
else
printf("栈不为空\n");
break;
case 8:
s = DestroyStack(S);
if (s)
printf("销毁栈成功\n");
else
printf("销毁栈失败\n");
break;
case 9:
Conversion();
break;
// case 10:
// BracketMatch();
// break;
case 0:
printf("程序结束,谢谢使用\n\n");
exit(0);
}
}
return 0;
}
@@ -0,0 +1,74 @@
// 预编译命令
#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define STACK_INIT_SIZE 10 // 顺序栈存储空间的初始分配量
#define STACKINCREMENT 2 // 顺序栈存储空间的分配增量
// 数据结构
typedef int Status;
typedef int SElemType; // 完成数制转换
// typedef char SElemType; //完成括号匹配
typedef struct {
SElemType *base; // 存储空间基址
SElemType *top; // 存储空间基址
int stacksize; // 当前分配的存储容量(以sizeof(ElemType)为单位)
} SqStack;
// 构造一个最大空间为 STACK_INIT_SIZE的空顺序栈S
Status InitStack(SqStack &S) {
S.base = (SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType));
if (!S.base)
exit(OVERFLOW); // 存储分配失败
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;
return OK;
}
// 栈不空,则用e返回栈顶元素
Status GetTop(SqStack S, SElemType &e) {
if (S.top == S.base)
return ERROR;
e = *(S.top - 1);
return OK;
}
// 给定值e入栈
Status Push(SqStack &S, SElemType e) {
if (S.top - S.base >= S.stacksize) {
S.base = (SElemType *)realloc(S.base, (S.stacksize + STACKINCREMENT) * sizeof(SElemType));
S.top = S.base + S.stacksize;
S.stacksize += STACKINCREMENT;
}
*S.top++ = e;
return OK;
}
// 若栈不空,则删除S的栈顶元素,
// 用 e 返回其值,并返回OK;
// 否则返回ERROR
Status Pop(SqStack &S, SElemType &e) {
if (S.top == S.base)
return ERROR;
e = *--S.top;
return OK;
}
// 判断栈空否
Status StackEmpty(SqStack S) {
if (S.top == S.base)
return OK;
else
return ERROR;
}
// 销毁栈
Status DestroyStack(SqStack &S) {
if (!S.base)
return ERROR;
free(S.base);
return OK;
}
@@ -0,0 +1,95 @@
#include <stdio.h>
#define MAXSIZE 50
typedef struct
{
int data[MAXSIZE];
int size;
} seqlist;
void seqlist_init(seqlist *list) {
list->size = 0;
}
void insert(seqlist *list, int position, int data) {
if (list->size == MAXSIZE) {
printf("seqlist is full\n");
return;
}
if (position < 0 || position > list->size) {
printf("position is out of range\n");
return;
}
for (int i = list->size - 1; i >= position; i--) {
list->data[i + 1] = list->data[i];
}
list->data[position] = data;
list->size++;
}
void delete(seqlist *list, int position) {
if (list->size == MAXSIZE) {
printf("seqlist is full\n");
return;
}
if (position < 0 || position >= list->size) {
printf("position is out of range\n");
return;
}
for (int i = position; i <= list->size - 1; i++) {
list->data[i] = list->data[i + 1];
}
list->size--;
}
int get(seqlist *list, int position) {
if (position < 0 || position >= list->size) {
printf("获取位置不合法\n");
return -1; // 返回一个特殊值表示错误
}
return list->data[position];
}
int search(seqlist *list, int data) {
for (int i = 0; i < list->size; i++) {
if (list->data[i] == data)
return i;
}
return -1;
}
void printSeqList(seqlist *list) {
printf("顺序表元素: ");
for (int i = 0; i < list->size; i++) {
printf("%d ", list->data[i]);
}
printf("\n");
}
int main() {
seqlist myList;
seqlist_init(&myList);
insert(&myList, 0, 1);
insert(&myList, 1, 2);
insert(&myList, 2, 3);
printSeqList(&myList);
delete (&myList, 1);
printSeqList(&myList);
int value = get(&myList, 1);
if (value != -1) {
printf("位置1的元素为: %d\n", value);
}
int position = search(&myList, 3);
if (position != -1) {
printf("元素3的位置为: %d\n", position);
}
return 0;
}
@@ -0,0 +1,185 @@
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node *creat_front(int num[], int lenth) {
Node *head = NULL;
for (int i = 0; i < lenth; i++) {
Node *new_node = (Node *)malloc(sizeof(Node));
if (new_node == NULL) {
printf("Failed to allocate\n");
exit(1);
}
new_node->data = num[i];
new_node->next = head;
head = new_node;
}
return head;
}
Node *creat_back(int num[], int lenth) {
Node *head = NULL;
Node *back = NULL;
for (int i = 0; i < lenth; i++) {
Node *new_node = (Node *)malloc(sizeof(Node));
if (new_node == NULL) {
printf("Failed to allocate\n");
exit(1);
}
new_node->data = num[i];
new_node->next = NULL;
if (head == NULL) {
head = new_node;
back = new_node;
}
else {
back->next = new_node;
back = new_node;
}
}
return head;
}
int get_list(Node *head, int position) {
Node *q = head;
int i = 0;
while (q != NULL) {
if (i == position) {
return q->data;
}
else {
q = q->next;
i++;
}
}
if (q == NULL)
printf("position is out of range and fail to get data!\n");
free(q);
return -1;
}
Node *insert(Node *head, int position, int data) {
Node *newNode = (Node *)malloc(sizeof(Node));
if (newNode == NULL) {
printf("fail to allocate!\n");
exit(1);
}
newNode->data = data;
if (position == 0) {
newNode->next = head;
head = newNode;
}
else {
Node *current = head;
int index = 0;
while (current != NULL && index < position - 1) {
current = current->next;
index++;
}
if (current != NULL) {
newNode->next = current->next;
current->next = newNode;
}
else {
printf("插入位置不合法\n");
free(newNode);
}
}
return head;
}
int findElement(Node *head, int value) {
Node *current = head;
int i = 0;
while (current != NULL) {
if (current->data == value) {
return i;
}
current = current->next;
i++;
}
exit(i);
}
Node *deleteElement(Node *head, int position) {
if (head == NULL) {
printf("链表为空\n");
return NULL;
}
Node *temp;
if (position == 0) {
temp = head;
head = head->next;
}
else {
Node *current = head;
int index = 0;
while (current != NULL && index < position - 1) {
current = current->next;
index++;
}
if (current != NULL && current->next != NULL) {
temp = current->next;
current->next = current->next->next;
}
else {
printf("删除位置不合法\n");
return head;
}
}
free(temp);
return head;
}
void printList(Node *head) {
Node *current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
int a[] = { 5, 6, 8, 9, 1 };
Node *myList = creat_front(a, 5);
printf("List after front insertion: ");
printList(myList);
free(myList);
myList = creat_back(a, 5);
printf("List after end insertion: ");
printList(myList);
int valueAtIndex2 = get_list(myList, 2);
printf("Value at index 2: %d\n", valueAtIndex2);
int searchResult = findElement(myList, 8);
printf("Index of value 8: %d\n", searchResult);
myList = insert(myList, 2, 10);
printf("List after insertion at index 2: ");
printList(myList);
myList = deleteElement(myList, 3);
printf("List after deletion at index 3: ");
printList(myList);
free(myList);
return 0;
}
@@ -0,0 +1,84 @@
#include <stdio.h>
// 定义多项式的项
typedef struct
{
int coefficient; // 系数
int exponent; // 指数
} Term;
// 函数声明
void addPolynomials(Term poly1[], int n1, Term poly2[], int n2, Term result[], int *nResult);
int main() {
int n1, n2;
// 输入第一个多项式的项数
printf("第一个多项式\n项数:");
scanf("%d", &n1);
// 输入第一个多项式的各项系数和指数
Term poly1[n1];
for (int i = 0; i < n1; i++) {
printf("第%d项系数和指数:", i + 1);
scanf("%d %d", &poly1[i].coefficient, &poly1[i].exponent);
}
// 输入第二个多项式的项数
printf("\n第二个多项式\n项数:");
scanf("%d", &n2);
// 输入第二个多项式的各项系数和指数
Term poly2[n2];
for (int i = 0; i < n2; i++) {
printf("第%d项系数和指数:", i + 1);
scanf("%d %d", &poly2[i].coefficient, &poly2[i].exponent);
}
// 计算两个多项式的和
int nResult = n1 + n2;
Term result[nResult];
addPolynomials(poly1, n1, poly2, n2, result, &nResult);
// 输出结果
printf("\n和多项式的各项为:\n");
for (int i = 0; i < nResult; i++) {
printf("第%d项,系数:%d,指数:%d\n", i + 1, result[i].coefficient, result[i].exponent);
}
return 0;
}
// 实现多项式相加的函数
void addPolynomials(Term poly1[], int n1, Term poly2[], int n2, Term result[], int *nResult) {
int i = 0, j = 0, k = 0;
// 循环遍历两个多项式的项
while (i < n1 && j < n2) {
// 比较当前项的指数大小
if (poly1[i].exponent > poly2[j].exponent) {
result[k++] = poly1[i++];
}
else if (poly1[i].exponent < poly2[j].exponent) {
result[k++] = poly2[j++];
}
else {
// 指数相等时,系数相加
result[k].exponent = poly1[i].exponent;
result[k++].coefficient = poly1[i++].coefficient + poly2[j++].coefficient;
}
}
// 处理多项式1剩余的项
while (i < n1) {
result[k++] = poly1[i++];
}
// 处理多项式2剩余的项
while (j < n2) {
result[k++] = poly2[j++];
}
// 更新结果多项式的项数
*nResult = k;
}
@@ -0,0 +1,193 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 学生结构体
typedef struct
{
int id;
char name[5];
} Student;
// 链表节点结构体
typedef struct Node {
Student student;
struct Node *next;
} Node;
// 链表结构体
typedef struct
{
Node *head;
} LinkedList;
// 函数声明
void initList(LinkedList *list);
void insertStudent(LinkedList *list, Student student);
void printList(LinkedList list);
Node *findStudentById(LinkedList list, int id);
void deleteStudentById(LinkedList *list, int id);
void clearList(LinkedList *list);
int main() {
LinkedList studentList;
initList(&studentList);
int choice;
do {
// 用户菜单
printf("\n学生管理系统菜单:\n");
printf("1. 添加学生\n");
printf("2. 删除学生\n");
printf("3. 查找学生\n");
printf("4. 打印学生列表\n");
printf("5. 清空学生列表\n");
printf("6. 退出\n");
printf("请选择操作(1-6): ");
scanf("%d", &choice);
switch (choice) {
case 1: {
// 添加学生
Student newStudent;
printf("请输入学号(1-100): ");
scanf("%d", &newStudent.id);
printf("请输入姓名(不超过4个字符): ");
scanf("%s", newStudent.name);
insertStudent(&studentList, newStudent);
break;
}
case 2: {
// 删除学生
int id;
printf("请输入要删除学生的学号: ");
scanf("%d", &id);
deleteStudentById(&studentList, id);
break;
}
case 3: {
// 查找学生
int id;
printf("请输入要查找学生的学号: ");
scanf("%d", &id);
Node *foundStudent = findStudentById(studentList, id);
if (foundStudent != NULL) {
printf("找到学生:学号 %d,姓名 %s\n", foundStudent->student.id, foundStudent->student.name);
}
else {
printf("未找到学生。\n");
}
break;
}
case 4:
// 打印学生列表
printList(studentList);
break;
case 5:
// 清空学生列表
clearList(&studentList);
printf("学生列表已清空。\n");
break;
case 6:
// 退出程序
printf("程序已退出。\n");
break;
default:
printf("无效的选择,请重新输入。\n");
}
} while (choice != 6);
return 0;
}
// 初始化链表
void initList(LinkedList *list) {
list->head = NULL;
}
// 在有序链表中插入学生
void insertStudent(LinkedList *list, Student student) {
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->student = student;
newNode->next = NULL;
if (list->head == NULL || student.id < list->head->student.id) {
// 插入头部
newNode->next = list->head;
list->head = newNode;
}
else {
// 插入中间或尾部
Node *current = list->head;
while (current->next != NULL && student.id > current->next->student.id) {
current = current->next;
}
newNode->next = current->next;
current->next = newNode;
}
printf("学生已添加:学号 %d,姓名 %s\n", student.id, student.name);
}
// 打印学生列表
void printList(LinkedList list) {
Node *current = list.head;
printf("\n学生列表:\n");
while (current != NULL) {
printf("学号 %d,姓名 %s\n", current->student.id, current->student.name);
current = current->next;
}
}
// 根据学号查找学生
Node *findStudentById(LinkedList list, int id) {
Node *current = list.head;
while (current != NULL) {
if (current->student.id == id) {
return current;
}
current = current->next;
}
return NULL;
}
// 根据学号删除学生
void deleteStudentById(LinkedList *list, int id) {
Node *current = list->head;
Node *prev = NULL;
while (current != NULL && current->student.id != id) {
prev = current;
current = current->next;
}
if (current != NULL) {
// 找到学生,进行删除操作
if (prev == NULL) {
// 删除头节点
list->head = current->next;
}
else {
prev->next = current->next;
}
free(current);
printf("学生已删除:学号 %d\n", id);
}
else {
printf("未找到学生。\n");
}
}
// 清空学生列表
void clearList(LinkedList *list) {
Node *current = list->head;
while (current != NULL) {
Node *next = current->next;
free(current);
current = next;
}
list->head = NULL;
}
@@ -0,0 +1,106 @@
#include <iostream>
#include <queue>
using namespace std;
struct TreeNode {
char data;
TreeNode *left;
TreeNode *right;
};
// 创建二叉树
TreeNode *create() {
char ch;
cin >> ch;
if (ch == '#')
return nullptr;
TreeNode *node = new TreeNode();
node->data = ch;
node->left = create();
node->right = create();
return node;
}
// 销毁二叉树
void destroy(TreeNode *root) {
if (root == nullptr)
return;
destroy(root->left);
destroy(root->right);
delete root;
}
// 先序遍历
void preOrder(TreeNode *root) {
if (root == nullptr)
return;
cout << root->data << ' ';
preOrder(root->left);
preOrder(root->right);
}
// 中序遍历
void inOrder(TreeNode *root) {
if (root == nullptr)
return;
inOrder(root->left);
cout << root->data << ' ';
inOrder(root->right);
}
// 后序遍历
void postOrder(TreeNode *root) {
if (root == nullptr)
return;
postOrder(root->left);
postOrder(root->right);
cout << root->data << ' ';
}
// 层次遍历
void levelOrder(TreeNode *root) {
if (root == nullptr)
return;
queue<TreeNode *> q;
q.push(root);
while (!q.empty()) {
TreeNode *node = q.front();
q.pop();
cout << node->data << ' ';
if (node->left)
q.push(node->left);
if (node->right)
q.push(node->right);
}
}
// 用括号表示法输出二叉树
void printWithBrackets(TreeNode *root) {
if (root == nullptr)
return;
cout << root->data;
if (root->left || root->right) {
cout << '(';
printWithBrackets(root->left);
cout << ',';
printWithBrackets(root->right);
cout << ')';
}
}
int main() {
TreeNode *root = create();
preOrder(root);
cout << endl;
inOrder(root);
cout << endl;
postOrder(root);
cout << endl;
levelOrder(root);
cout << endl;
printWithBrackets(root);
cout << endl;
destroy(root);
return 0;
}
@@ -0,0 +1,80 @@
#include <iostream>
using namespace std;
// 定义线索二叉树节点
struct Node {
int data;
Node *left, *right;
int ltag, rtag; // 左右标志位,0表示指向子节点,1表示指向前驱或后继
};
Node *pre = NULL; // 全局变量,记录上一个访问的节点
// 创建线索二叉树
Node *createTree(int data) {
Node *node = new Node();
node->data = data;
node->left = node->right = NULL;
node->ltag = node->rtag = 0;
return node;
}
// 中序遍历线索化
void inThreading(Node *node) {
if (node) {
inThreading(node->left); // 递归左子树
if (!node->left) { // 如果该节点没有左孩子,设置ltag为1,并让left指向上一个节点
node->ltag = 1;
node->left = pre;
}
if (pre && !pre->right) { // 如果上一个节点没有右孩子,设置rtag为1,并让right指向当前节点
pre->rtag = 1;
pre->right = node;
}
pre = node;
inThreading(node->right); // 递归右子树
}
}
// 中序遍历线索二叉树
void inOrder(Node *node) {
while (node) {
while (!node->ltag) // 如果ltag为0,一直找到最左下节点
node = node->left;
cout << node->data << " ";
while (node->rtag) { // 如果rtag为1,一直找到最右下节点
node = node->right;
cout << node->data << " ";
}
node = node->right; // 转向右子树
}
}
// 查找节点的前驱
Node *findPredecessor(Node *node) {
if (node->ltag) // 如果ltag为1,left指向的就是前驱
return node->left;
else
return NULL;
}
// 查找节点的后继
Node *findSuccessor(Node *node) {
if (node->rtag) // 如果rtag为1,right指向的就是后继
return node->right;
else
return NULL;
}
// 主函数
int main() {
Node *root = createTree(1);
root->left = createTree(2);
root->right = createTree(3);
root->left->left = createTree(4);
root->left->right = createTree(5);
inThreading(root);
inOrder(root);
return 0;
}
@@ -0,0 +1,64 @@
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
struct Node {
int weight;
string code;
Node *left, *right;
Node(int w) : weight(w), left(NULL), right(NULL) {}
};
struct cmp {
bool operator()(Node *a, Node *b) {
return a->weight > b->weight;
}
};
void generateHuffmanCode(Node *root, string str) {
if (!root)
return;
if (!root->left && !root->right) {
root->code = str;
}
generateHuffmanCode(root->left, str + "0");
generateHuffmanCode(root->right, str + "1");
}
int main() {
int n;
cin >> n;
priority_queue<Node *, vector<Node *>, cmp> pq;
for (int i = 0; i < n; ++i) {
int w;
cin >> w;
pq.push(new Node(w));
}
while (pq.size() != 1) {
Node *left = pq.top();
pq.pop();
Node *right = pq.top();
pq.pop();
Node *parent = new Node(left->weight + right->weight);
parent->left = left;
parent->right = right;
pq.push(parent);
}
generateHuffmanCode(pq.top(), "");
vector<Node *> nodes;
nodes.push_back(pq.top());
while (!nodes.empty()) {
Node *node = nodes.back();
nodes.pop_back();
if (node->left)
nodes.push_back(node->left);
if (node->right)
nodes.push_back(node->right);
if (!node->left && !node->right) {
cout << node->code << " ";
}
}
return 0;
}
@@ -0,0 +1,59 @@
#include <iostream>
#include <map>
using namespace std;
class Node {
public:
string name;
map<string, Node *> children;
Node(string name) : name(name) {}
Node *find(string path) {
if (path.empty())
return this;
int pos = path.find('/');
string first = pos == string::npos ? path : path.substr(0, pos);
string rest = pos == string::npos ? "" : path.substr(pos + 1);
if (children.count(first) == 0)
return nullptr;
return children[first]->find(rest);
}
void add(string path) {
int pos = path.find('/');
string first = pos == string::npos ? path : path.substr(0, pos);
string rest = pos == string::npos ? "" : path.substr(pos + 1);
if (children.count(first) == 0)
children[first] = new Node(first);
if (!rest.empty())
children[first]->add(rest);
}
bool remove(string path) {
int pos = path.find('/');
string first = pos == string::npos ? path : path.substr(0, pos);
string rest = pos == string::npos ? "" : path.substr(pos + 1);
if (children.count(first) == 0)
return false;
if (rest.empty()) {
delete children[first];
children.erase(first);
return true;
}
return children[first]->remove(rest);
}
};
int main() {
Node root("/");
root.add("dir1/dir2/file");
cout << (root.find("dir1/dir2/file") != nullptr) << endl;
cout << (root.find("dir1/dir2") != nullptr) << endl;
cout << (root.find("dir1") != nullptr) << endl;
cout << (root.find("dir1/dir3") == nullptr) << endl;
root.remove("dir1/dir2/file");
cout << (root.find("dir1/dir2/file") == nullptr) << endl;
return 0;
}
@@ -0,0 +1,69 @@
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
using namespace std;
// 图的邻接矩阵存储
vector<vector<int>> adjMatrix;
// 图的邻接表存储
vector<vector<int>> adjList;
// 图的深度优先遍历
void DFS(int start, vector<bool> &visited) {
stack<int> s;
s.push(start);
visited[start] = true;
while (!s.empty()) {
int vertex = s.top();
s.pop();
cout << vertex << " ";
for (int i = 0; i < adjList[vertex].size(); i++) {
if (!visited[adjList[vertex][i]]) {
s.push(adjList[vertex][i]);
visited[adjList[vertex][i]] = true;
}
}
}
}
// 图的广度优先遍历
void BFS(int start, vector<bool> &visited) {
queue<int> q;
q.push(start);
visited[start] = true;
while (!q.empty()) {
int vertex = q.front();
q.pop();
cout << vertex << " ";
for (int i = 0; i < adjList[vertex].size(); i++) {
if (!visited[adjList[vertex][i]]) {
q.push(adjList[vertex][i]);
visited[adjList[vertex][i]] = true;
}
}
}
}
int main() {
int n, m;
cin >> n >> m; // 输入顶点数和边数
adjMatrix.resize(n, vector<int>(n, 0));
adjList.resize(n);
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v; // 输入边的两个顶点
adjMatrix[u][v] = 1;
adjMatrix[v][u] = 1;
adjList[u].push_back(v);
adjList[v].push_back(u);
}
vector<bool> visited(n, false);
DFS(0, visited); // 从顶点0开始深度优先遍历
cout << endl;
fill(visited.begin(), visited.end(), false);
BFS(0, visited); // 从顶点0开始广度优先遍历
return 0;
}
@@ -0,0 +1,92 @@
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
const int MAX = 1e9;
const int N = 6;
double graph[N][N] = {
{ 0, 0.6, 0.1, 0.5, 0, 0 },
{ 0.6, 0, 0.5, 0, 0.3, 0 },
{ 0.1, 0.5, 0, 0.5, 0.6, 0.4 },
{ 0.5, 0, 0.5, 0, 0, 0.2 },
{ 0, 0.3, 0.6, 0, 0, 0.6 },
{ 0, 0, 0.4, 0.2, 0.6, 0 }
};
// Prim's Algorithm
void prim() {
vector<bool> selected(N, false);
vector<double> minWeight(N, MAX);
minWeight[0] = 0;
for (int i = 0; i < N; ++i) {
int u = -1;
for (int j = 0; j < N; ++j) {
if (!selected[j] && (u == -1 || minWeight[j] < minWeight[u])) {
u = j;
}
}
selected[u] = true;
for (int v = 0; v < N; ++v) {
if (!selected[v] && graph[u][v] != 0 && graph[u][v] < minWeight[v]) {
minWeight[v] = graph[u][v];
}
}
}
double totalWeight = 0;
for (int i = 0; i < N; ++i) {
totalWeight += minWeight[i];
}
cout << "Minimum cost with Prim's Algorithm: " << totalWeight << endl;
}
// Kruskal's Algorithm
struct Edge {
int u, v;
double weight;
bool operator<(const Edge &other) const {
return weight < other.weight;
}
};
int parent[N];
int find(int x) {
if (x != parent[x]) {
parent[x] = find(parent[x]);
}
return parent[x];
}
void unionSet(int x, int y) {
parent[find(x)] = find(y);
}
void kruskal() {
vector<Edge> edges;
for (int i = 0; i < N; ++i) {
for (int j = i + 1; j < N; ++j) {
if (graph[i][j] > 0) {
edges.push_back({ i, j, graph[i][j] });
}
}
}
sort(edges.begin(), edges.end());
for (int i = 0; i < N; ++i) {
parent[i] = i;
}
double totalWeight = 0;
for (const Edge &edge : edges) {
if (find(edge.u) != find(edge.v)) {
totalWeight += edge.weight;
unionSet(edge.u, edge.v);
}
}
cout << "Minimum cost with Kruskal's Algorithm: " << totalWeight << endl;
}
int main() {
prim();
kruskal();
return 0;
}
@@ -0,0 +1,139 @@
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
// 定义课程结构体,包含课程号,学分,入度,邻接表
struct Course {
string id; // 课程号
int credit; // 学分
int indegree; // 入度
vector<int> adj; // 邻接表
Course(string i, int c) : id(i), credit(c), indegree(0) {} // 构造函数
};
// 定义拓扑排序函数,参数为课程数组,学期总数,每学期学分上限,课程总数
void topologicalSort(vector<Course> &courses, int term, int limit, int num) {
queue<int> q; // 定义一个队列,用于存放入度为0的课程
vector<int> result; // 定义一个数组,用于存放拓扑排序的结果
int count = 0; // 定义一个计数器,用于记录已经安排的课程数
// 遍历课程数组,将入度为0的课程入队,并输出
for (int i = 0; i < num; i++) {
if (courses[i].indegree == 0)
q.push(i);
}
// 当队列不为空时,循环执行以下操作
while (!q.empty()) {
int u = q.front(); // 取出队首元素
q.pop(); // 出队
result.push_back(u); // 将队首元素加入结果数组
count++; // 计数器加一
// 遍历队首元素的邻接表,将其邻接课程的入度减一,如果入度变为0,则入队
for (int v : courses[u].adj) {
courses[v].indegree--;
if (courses[v].indegree == 0) {
q.push(v);
}
}
}
// 如果计数器等于课程总数,说明拓扑排序成功,否则说明有环,无法完成所有课程
if (count == num) {
cout << "拓扑排序成功,结果为:" << endl;
// 输出拓扑排序结果
for (int i = 0; i < num; i++) {
cout << courses[result[i]].id << " ";
}
cout << endl;
// 定义一个二维数组,用于存放每个学期的课程安排
vector<vector<int>> plan(term);
// 定义一个变量,用于记录当前安排到哪个学期
int current = 0;
// 定义一个变量,用于记录当前学期的已安排学分
int credit = 0;
// 遍历拓扑排序结果,按照策略安排课程
for (int i = 0; i < num; i++) {
// 如果当前课程的学分加上已安排学分超过学分上限,或者当前学期已满,则安排到下一个学期
if (credit + courses[result[i]].credit > limit || plan[current].size() == term) {
current++;
credit = 0;
}
// 如果当前学期还有空余,且没有超过学分上限,则安排当前课程到当前学期
if (current < term && credit + courses[result[i]].credit <= limit) {
plan[current].push_back(result[i]);
credit += courses[result[i]].credit;
}
}
// 输出每个学期的课程安排
cout << "按照给定的条件,最少需要" << current + 1 << "个学期完成所有课程,具体安排如下:" << endl;
for (int i = 0; i <= current; i++) {
cout << "第" << i + 1 << "个学期的课程有:";
for (int j = 0; j < plan[i].size(); j++) {
cout << courses[plan[i][j]].id << " ";
}
cout << endl;
}
}
else {
cout << "拓扑排序失败,无法完成所有课程的学习" << endl;
}
}
// 定义主函数,用于测试代码的功能
int main() {
// 定义课程总数,学期总数,每学期学分上限
int num, term, limit;
// 从标准输入读取这些参数
cout << "请输入学期总数,每学期学分上限,课程总数,用空格隔开:" << endl;
cin >> term >> limit >> num;
// 定义一个课程数组,用于存放课程信息
vector<Course> courses;
// 初始化课程信息,根据题目给定的数据
courses.push_back(Course("C1", 2));
courses.push_back(Course("C2", 3));
courses.push_back(Course("C3", 4));
courses.push_back(Course("C4", 3));
courses.push_back(Course("C5", 2));
courses.push_back(Course("C6", 3));
courses.push_back(Course("C7", 4));
courses.push_back(Course("C8", 4));
courses.push_back(Course("C9", 5));
courses.push_back(Course("C10", 3));
courses.push_back(Course("C11", 2));
courses.push_back(Course("C12", 5));
courses.push_back(Course("C13", 3));
courses.push_back(Course("C14", 3));
// 初始化课程之间的先修关系,根据题目给定的数据
courses[0].adj.push_back(1); // C1 -> C2
courses[0].adj.push_back(2); // C1 -> C3
courses[0].adj.push_back(3); // C1 -> C4
courses[0].adj.push_back(11); // C1 -> C12
courses[0].adj.push_back(13); // C1 -> C14
courses[1].adj.push_back(2); // C2 -> C3
courses[2].adj.push_back(4); // C3 -> C5
courses[2].adj.push_back(6); // C3 -> C7
courses[2].adj.push_back(7); // C3 -> C8
courses[3].adj.push_back(4); // C4 -> C5
courses[3].adj.push_back(12); // C4 -> C13
courses[4].adj.push_back(6); // C5 -> C7
courses[5].adj.push_back(7); // C6 -> C8
courses[5].adj.push_back(12); // C6 -> C13
courses[5].adj.push_back(13); // C6 -> C14
courses[8].adj.push_back(5); // C9 -> C6
courses[8].adj.push_back(9); // C9 -> C10
courses[8].adj.push_back(10); // C9 -> C11
courses[8].adj.push_back(11); // C9 -> C12
courses[9].adj.push_back(11); // C10 -> C12
courses[10].adj.push_back(5); // C11 -> C6
courses[10].adj.push_back(13); // C11 -> C14
courses[12].adj.push_back(13); // C13 -> C14
// 更新每个课程的入度
for (int i = 0; i < num; i++) {
for (int j : courses[i].adj) {
courses[j].indegree++;
}
}
// 调用拓扑排序函数,输出结果
topologicalSort(courses, term, limit, num);
return 0;
}
@@ -0,0 +1,64 @@
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
#define INF INT_MAX
#define N 6
void Dijkstra(int graph[N][N], int start) {
vector<int> dist(N, INF);
dist[start] = 0;
vector<bool> visited(N, false);
vector<int> prev(N, -1);
for (int count = 0; count < N - 1; count++) {
int min = INF, min_index;
for (int v = 0; v < N; v++)
if (!visited[v] && dist[v] <= min)
min = dist[v], min_index = v;
int u = min_index;
visited[u] = true;
for (int v = 0; v < N; v++)
if (!visited[v] && graph[u][v] && dist[u] != INF && dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
prev[v] = u;
}
}
for (int i = 0; i < N; i++) {
if (i != start) {
cout << "Path from " << start << " to " << i << ": ";
if (dist[i] == INF) {
cout << "No path\n";
}
else {
vector<int> path;
for (int j = i; j != -1; j = prev[j])
path.push_back(j);
for (int j = path.size() - 1; j > 0; j--)
cout << path[j] << " -> ";
cout << path[0] << " (Cost: " << dist[i] << ")\n";
}
}
}
}
int main() {
int graph[N][N] = {
{ 0, 0, 10, 0, 30, 100 },
{ 0, 0, 5, 0, 0, 0 },
{ 0, 0, 0, 50, 0, 0 },
{ 0, 0, 0, 0, 0, 10 },
{ 0, 0, 0, 20, 0, 60 },
{ 0, 0, 0, 0, 0, 0 }
};
for (int i = 0; i < N; i++)
Dijkstra(graph, i);
return 0;
}
@@ -0,0 +1,109 @@
#include <iostream>
#include <limits>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// 插入节点
TreeNode *insertNode(TreeNode *root, int val) {
if (root == NULL) {
return new TreeNode(val);
}
if (val < root->val) {
root->left = insertNode(root->left, val);
}
else if (val > root->val) {
root->right = insertNode(root->right, val);
}
return root;
}
// 删除节点
TreeNode *deleteNode(TreeNode *root, int key) {
if (root == NULL)
return root;
if (key < root->val) {
root->left = deleteNode(root->left, key);
}
else if (key > root->val) {
root->right = deleteNode(root->right, key);
}
else {
if (root->left == NULL) {
TreeNode *temp = root->right;
delete root;
return temp;
}
else if (root->right == NULL) {
TreeNode *temp = root->left;
delete root;
return temp;
}
TreeNode *temp = root->right;
while (temp && temp->left != NULL)
temp = temp->left;
root->val = temp->val;
root->right = deleteNode(root->right, temp->val);
}
return root;
}
// 判断是否为二叉搜索树
bool isValidBST(TreeNode *root, TreeNode *minNode = NULL, TreeNode *maxNode = NULL) {
if (root == NULL)
return true;
if (minNode != NULL && root->val <= minNode->val || maxNode != NULL && root->val >= maxNode->val) {
return false;
}
return isValidBST(root->left, minNode, root) && isValidBST(root->right, root, maxNode);
}
// 查找最大值和第二大值
pair<int, int> findMaxAndSecondMax(TreeNode *root) {
int maxVal = numeric_limits<int>::min();
int secondMaxVal = numeric_limits<int>::min();
TreeNode *curr = root;
while (curr) {
if (curr->val > maxVal) {
secondMaxVal = maxVal;
maxVal = curr->val;
}
else if (curr->val > secondMaxVal && curr->val < maxVal) {
secondMaxVal = curr->val;
}
curr = curr->right;
}
return { maxVal, secondMaxVal };
}
// 主函数,用于测试以上所有功能
int main() {
int n;
TreeNode *root = NULL;
cout << "Enter a number to insert: ";
while (true) {
int val;
cin >> val;
if (val == -1)
break;
root = insertNode(root, val);
}
cout << "Is valid BST: " << (isValidBST(root) ? "Yes" : "No") << endl;
auto maxAndSecondMax = findMaxAndSecondMax(root);
cout << "Max: " << maxAndSecondMax.first << ", Second Max: " << maxAndSecondMax.second << endl;
cout << "Enter a number to delete: ";
cin >> n;
root = deleteNode(root, n);
cout << "After deleting " << n << ", is valid BST: " << (isValidBST(root) ? "Yes" : "No") << endl;
return 0;
}
@@ -0,0 +1,123 @@
#include <iostream>
using namespace std;
struct Node {
int key;
Node *left;
Node *right;
int height;
};
Node *newNode(int key) {
Node *node = new Node();
node->key = key;
node->left = NULL;
node->right = NULL;
node->height = 1;
return (node);
}
int height(Node *N) {
if (N == NULL)
return 0;
return N->height;
}
int max(int a, int b) {
return (a > b) ? a : b;
}
Node *rightRotate(Node *y) {
Node *x = y->left;
Node *T2 = x->right;
x->right = y;
y->left = T2;
y->height = max(height(y->left), height(y->right)) + 1;
x->height = max(height(x->left), height(x->right)) + 1;
return x;
}
Node *leftRotate(Node *x) {
Node *y = x->right;
Node *T2 = y->left;
y->left = x;
x->right = T2;
x->height = max(height(x->left), height(x->right)) + 1;
y->height = max(height(y->left), height(y->right)) + 1;
return y;
}
int getBalance(Node *N) {
if (N == NULL)
return 0;
return height(N->left) - height(N->right);
}
Node *insert(Node *node, int key) {
if (node == NULL)
return (newNode(key));
if (key < node->key)
node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);
else
return node;
node->height = 1 + max(height(node->left), height(node->right));
int balance = getBalance(node);
if (balance > 1 && key < node->left->key)
return rightRotate(node);
if (balance < -1 && key > node->right->key)
return leftRotate(node);
if (balance > 1 && key > node->left->key) {
node->left = leftRotate(node->left);
return rightRotate(node);
}
if (balance < -1 && key < node->right->key) {
node->right = rightRotate(node->right);
return leftRotate(node);
}
return node;
}
void preOrder(Node *root) {
if (root != NULL) {
cout << root->key << " ";
preOrder(root->left);
preOrder(root->right);
}
}
bool isBalanced(Node *root) {
int balance = getBalance(root);
if (balance > 1 || balance < -1)
return false;
else
return true;
}
int main() {
Node *root = NULL;
while (true) {
int val;
cin >> val;
if (val == -1)
break;
root = insert(root, val);
}
if (isBalanced(root))
cout << "The tree is balanced.\n";
else
cout << "The tree is not balanced.\n";
cout << "Preorder traversal of the constructed AVL tree is \n";
preOrder(root);
return 0;
}
@@ -0,0 +1,68 @@
#include <iostream>
#include <vector>
#include <list>
#include <string>
#include <cmath>
using namespace std;
const int Base = 31;
const int TableSize = 1000;
struct Node {
string key;
int value;
Node(string key, int value) : key(key), value(value) {}
};
class HashTable {
private:
vector<list<Node>> table;
int hashFunc(string key) {
int hashVal = 0;
for (int i = 0; i < key.length(); i++) {
hashVal = (hashVal + key[i] * static_cast<long long>(pow(Base, i))) % TableSize;
}
return hashVal;
}
public:
HashTable() {
table.resize(TableSize);
}
void insert(string key, int value) {
int hashVal = hashFunc(key);
for (auto &node : table[hashVal]) {
if (node.key == key) {
node.value = value;
return;
}
}
table[hashVal].push_back(Node(key, value));
}
int search(string key) {
int hashVal = hashFunc(key);
for (auto &node : table[hashVal]) {
if (node.key == key) {
return node.value;
}
}
return -1;
}
void destroy() {
for (auto &bucket : table) {
bucket.clear();
}
}
};
int main() {
HashTable ht;
ht.insert("Alice", 1);
ht.insert("Bob", 2);
cout << "Alice: " << ht.search("Alice") << endl;
cout << "Bob: " << ht.search("Bob") << endl;
cout << "Charlie: " << ht.search("Charlie") << endl;
ht.destroy();
return 0;
}
@@ -0,0 +1,152 @@
#include <vector>
#include <iostream>
using namespace std;
// 选择排序
void selectionSort(vector<int> &nums) {
int n = nums.size();
for (int i = 0; i < n; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (nums[j] < nums[minIndex]) {
minIndex = j;
}
}
swap(nums[i], nums[minIndex]);
}
}
// 插入排序
void insertionSort(vector<int> &nums) {
int n = nums.size();
for (int i = 1; i < n; i++) {
int key = nums[i];
int j = i - 1;
while (j >= 0 && nums[j] > key) {
nums[j + 1] = nums[j];
j--;
}
nums[j + 1] = key;
}
}
// 归并排序
void merge(vector<int> &nums, int left, int mid, int right) {
vector<int> temp(right - left + 1);
int i = left, j = mid + 1, k = 0;
while (i <= mid && j <= right) {
temp[k++] = nums[i] <= nums[j] ? nums[i++] : nums[j++];
}
while (i <= mid) {
temp[k++] = nums[i++];
}
while (j <= right) {
temp[k++] = nums[j++];
}
for (int i = left; i <= right; i++) {
nums[i] = temp[i - left];
}
}
void mergeSort(vector<int> &nums, int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
mergeSort(nums, left, mid);
mergeSort(nums, mid + 1, right);
merge(nums, left, mid, right);
}
}
// 单指针快速排序
int partitionSingle(vector<int> &nums, int left, int right) {
int pivot = nums[right];
int i = left;
for (int j = left; j < right; j++) {
if (nums[j] < pivot) {
swap(nums[i], nums[j]);
i++;
}
}
swap(nums[i], nums[right]);
return i;
}
void quickSortSingle(vector<int> &nums, int left, int right) {
if (left < right) {
int pivotIndex = partitionSingle(nums, left, right);
quickSortSingle(nums, left, pivotIndex - 1);
quickSortSingle(nums, pivotIndex + 1, right);
}
}
// 双指针快速排序
int partitionDouble(vector<int> &nums, int left, int right) {
int pivot = nums[left];
while (left < right) {
while (left < right && nums[right] >= pivot) {
right--;
}
nums[left] = nums[right];
while (left < right && nums[left] <= pivot) {
left++;
}
nums[right] = nums[left];
}
nums[left] = pivot;
return left;
}
void quickSortDouble(vector<int> &nums, int left, int right) {
if (left < right) {
int pivotIndex = partitionDouble(nums, left, right);
quickSortDouble(nums, left, pivotIndex - 1);
quickSortDouble(nums, pivotIndex + 1, right);
}
}
// 主函数,用于测试上述排序算法
int main() {
vector<int> arr;
int n;
cout << "请输入你想要排序的数字的数量:";
cin >> n;
cout << "请输入这些数字(用空格隔开):";
for (int i = 0; i < n; i++) {
int num;
cin >> num;
arr.push_back(num);
}
selectionSort(arr);
cout << "选择排序后的数组:";
for (int i = 0; i < arr.size(); i++)
cout << arr[i] << " ";
cout << "\n";
insertionSort(arr);
cout << "插入排序后的数组:";
for (int i = 0; i < arr.size(); i++)
cout << arr[i] << " ";
cout << "\n";
mergeSort(arr, 0, arr.size() - 1);
cout << "归并排序后的数组:";
for (int i = 0; i < arr.size(); i++)
cout << arr[i] << " ";
cout << "\n";
quickSortSingle(arr, 0, arr.size() - 1);
cout << "单指针快速排序后的数组:";
for (int i = 0; i < arr.size(); i++)
cout << arr[i] << " ";
cout << "\n";
quickSortDouble(arr, 0, arr.size() - 1);
cout << "双指针快速排序后的数组:";
for (int i = 0; i < arr.size(); i++)
cout << arr[i] << " ";
cout << "\n";
return 0;
}
@@ -0,0 +1,83 @@
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
// 输入数组元素的函数
vector<int> inputArray(int n) {
vector<int> arr;
int temp;
cout << "请输入数组的元素:";
for (int i = 0; i < n; i++) {
cin >> temp;
arr.push_back(temp);
}
return arr;
}
// 方案一:使用优先队列
void heapSortUsingPriorityQueue(vector<int> &arr) {
priority_queue<int, vector<int>, greater<int>> pq(arr.begin(), arr.end());
int i = 0;
while (!pq.empty()) {
arr[i++] = pq.top();
pq.pop();
}
}
// 方案二:使用向下过滤函数
void heapify(vector<int> &arr, int n, int i) {
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < n && arr[left] > arr[largest])
largest = left;
if (right < n && arr[right] > arr[largest])
largest = right;
if (largest != i) {
swap(arr[i], arr[largest]);
heapify(arr, n, largest);
}
}
void heapSort(vector<int> &arr) {
int n = arr.size();
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
for (int i = n - 1; i >= 0; i--) {
swap(arr[0], arr[i]);
heapify(arr, i, 0);
}
}
void printArray(vector<int> &arr) {
for (int i = 0; i < arr.size(); ++i)
cout << arr[i] << " ";
cout << "\n";
}
int main() {
int n;
cout << "请输入数组的元素个数:";
cin >> n;
vector<int> arr = inputArray(n);
heapSortUsingPriorityQueue(arr);
cout << "Sorted array using priority queue is \n";
printArray(arr);
arr = inputArray(n);
heapSort(arr);
cout << "Sorted array using heapify is \n";
printArray(arr);
}