1,KMP算法
void preKmp(char *x, int m, int kmpNext[])

{

int i, j;
i = 0;
j = kmpNext[0] = -1;


while (i < m)
{
while (j > -1 && x[i] != x[j])
j = kmpNext[j];
i++;
j++;
if (x[i] == x[j])
kmpNext[i] = kmpNext[j];
else
kmpNext[i] = j;
}
}


void KMP(char *x, int m, char *y, int n)


{//x为模式串,m为其长度,y为主串,n为其长度

int i, j, kmpNext[MAXSIZE];//kmpNext数组存放next函数值


/**//* Preprocessing */
preKmp(x, m, kmpNext);


/**//* Searching */
i = j = 0;

while (j < n)
{
while (i > -1 && x[i] != y[j])
i = kmpNext[i];
i++;
j++;

if (i >= m)
{
OUTPUT(j - i);
i = kmpNext[i];
}
}
}

2,二叉排序树的建立及查找算法
#include <stdlib.h>
#include <stdio.h>
#define NULL 0
typedef int KeyType;
typedef struct


{
KeyType key;
}ElemType; //元素类型
typedef struct BiTNode


{
ElemType data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
BiTree find(BiTree root,KeyType key)


{ //在二叉排序树中查找其关键字等于给定值的结点是否存在,并输出相应信息
BiTNode *p;
p=root;
if (p==NULL) return NULL;
else if (p->data.key==key) return p;
else if (key<p->data.key) return find(p->lchild,key);
else return find(p->rchild,key);
}

void Insert(BiTree *p,BiTree t)
{ //在二叉排序树中插入一个新结点
if (*p==NULL) *p=t;
else if(t->data.key<(*p)->data.key) Insert(&((*p)->lchild),t);
else if(t->data.key>(*p)->data.key) Insert(&((*p)->rchild),t);
}

void inorder(BiTree p)
{ //中序遍历所建二叉排序树,将得到一个按关键字有序的元素序列

if(p!=NULL)
{
inorder(p->lchild);
printf("%5d",(p->data).key);
inorder(p->rchild);
}
}

void main()
{
char ch;
KeyType key;
BiTree p,s;
int i=0;
printf("Please input datas (9999:end):\n");//建立一棵二叉排序树,元素值从键盘输入,直到输入关键字等于9999为止
scanf("%4d",&key);
p=NULL;

while(key!=9999)
{
s=(BiTree)malloc(sizeof(BiTNode));
(s->data).key=key;
s->lchild=s->rchild=NULL;
Insert(&p,s);
scanf("%d",&key);
}
printf("Create is completed\n");
inorder(p); //中序遍历已建立的二叉排序树
printf("\n");

do
{ //二叉排序树的查找,可多次查找,并输出查找的结果
printf("Input the key you want to search:");
scanf("%4d",&key);
s=find(p,key);
if (s!=NULL) printf("success,the value is %4d ",s->data.key);
else printf("unsuccess");
printf("\ncontinue?y:n\n");getchar();
ch=getchar();
}while(ch=='y'||ch=='Y');
}


【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述