热身赛-哈希表
This commit is contained in:
parent
1a6ee0234b
commit
846c8e5d30
|
@ -11,16 +11,81 @@
|
|||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
// #include <user_api.h>
|
||||
#include <transform.h>
|
||||
|
||||
#define MAX 3 // MAX为哈希表的大小,定义为3
|
||||
|
||||
extern int FrameworkInit();
|
||||
extern void ApplicationOtaTaskInit(void);
|
||||
int main(void)
|
||||
|
||||
typedef struct node //构建结构体node
|
||||
{
|
||||
printf("Hello, world! \n");
|
||||
int first;
|
||||
int second;
|
||||
struct node *next;
|
||||
} NODE;
|
||||
void Hash(NODE *M) //初始化哈希表
|
||||
{
|
||||
int i;
|
||||
for (i = 0; i < MAX; i++)
|
||||
{
|
||||
M[i].next = NULL;
|
||||
}
|
||||
}
|
||||
void CreateHash(NODE *M, int first, int second) //将数据插入哈希表
|
||||
{
|
||||
NODE *s;
|
||||
s = (NODE *)malloc(sizeof(NODE));
|
||||
s->first = first;
|
||||
s->second = second;
|
||||
s->next = NULL;
|
||||
int index = first % MAX; //计算要插入的位置
|
||||
if (M[index].next == NULL) //判断该位置是否存在节点
|
||||
{
|
||||
M[index].next = s; //如果为空直接插入
|
||||
}
|
||||
else
|
||||
{
|
||||
NODE *tail = M[index].next;
|
||||
while (tail->next != NULL) //遍历链表找到末尾,插入节点
|
||||
{
|
||||
tail = tail->next;
|
||||
}
|
||||
tail->next = s;
|
||||
}
|
||||
}
|
||||
|
||||
int main(void)
|
||||
{
|
||||
NODE *M, *p; //声明两个指针,用于操作哈希表和遍历链表
|
||||
int n = 5, second, i = 0; //定义五个数
|
||||
int first;
|
||||
M = (NODE *)malloc(sizeof(NODE) * MAX);
|
||||
Hash(M); //初始化哈希表
|
||||
CreateHash(M, 1, 50); //将(1,50)插入哈希表中
|
||||
CreateHash(M, 2, 40);
|
||||
CreateHash(M, 3, 70);
|
||||
CreateHash(M, 4, 60);
|
||||
CreateHash(M, 5, 100);
|
||||
printf("number: 1,50\n");
|
||||
printf("number: 2,40\n");
|
||||
printf("number: 3,70\n");
|
||||
printf("number: 4,60\n");
|
||||
printf("number: 5,100\n");
|
||||
for (i = 0; i < MAX; i++) //循环遍历哈希表的所有位置
|
||||
{
|
||||
printf("Hash Slot %d:", i);
|
||||
p = M[i].next; //将指针p指向当前位置的链表头
|
||||
while (p != NULL)
|
||||
{
|
||||
printf("->%d", p->second);
|
||||
p = p->next; //将指针p移动到链表的下一节点
|
||||
}
|
||||
printf("\n");
|
||||
}
|
||||
|
||||
FrameworkInit();
|
||||
#ifdef APPLICATION_OTA
|
||||
ApplicationOtaTaskInit();
|
||||
|
|
Loading…
Reference in New Issue