ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

利用哈希算法找两个文件代码行不同的C语言代码

2020-09-25 09:31:22  阅读:203  来源: 互联网

标签:node 哈希 int 代码 C语言 str printf buf BUFF


先上代码

#include<stdio.h>
#include <string.h>
#include<stdlib.h>
const int maxn = 100000000;

typedef struct NODE{
 struct NODE* next;
 char* str;
}Node;
Node BUFF[100000000];

unsigned int ELFHash(char* str){
  unsigned int hash=0;
  unsigned int x=0;
  while(*str){
   
//   printf("%d\n", *str); 
   hash=(hash<<4)+(*str++);
   if((x=hash&0xF0000000L)!=0){
    hash^=(x>>24);
    hash&=~x;
   }
  }
  return (hash&0x7FFFFFFF);
 }
 
int main(){
// for(int i = 0; i < maxn; i++){
// 	BUFF[i].next = NULL;
// 	BUFF[i].str = NULL;
// }
 FILE *fp;
 Node* node;
 fp=fopen("dict.txt","r");
 char buf[100]= {'\0'};
 while(fgets(buf, 100, fp)!=NULL){
 	int i;
  for(i = 0; i < 100; i++){
//   printf("%c", buf[i]);
   if(buf[i] == '\n'){
    buf[i] = '\0';
    break;
   }
  }
//  printf("%s %d\n", buf, ELFHash(buf));
  int pos = ELFHash(buf)%maxn;
  if(BUFF[pos].str == NULL){
  	BUFF[pos].str = (char*)malloc(i+1);
  	strcpy(BUFF[pos].str, buf);
  }
  else{
   node = &BUFF[pos];
   while(node->next){
    node = node->next;
   }
   Node* newNode = (Node*)malloc(sizeof(Node));
	newNode->str = (char*)malloc(i+1);
	strcpy(newNode->str, buf);
   newNode->next = NULL;
   node->next = newNode;
  } 
//  printf("%s", BUFF[ELFHash(buf)%maxn].str);
//  char buf[100]= {'\0'};
//  getchar();
 }
// printf("建表完成");
// getchar();
 int res = 0;
 fp = fopen("string.txt", "r");
// buf[100] = {'\0'};
//memset(buf, '\0', 100);
 while(fgets(buf, 100, fp) != NULL){
  for(int i = 0; i < 100; i++){
   if(buf[i] == '\n'){
    buf[i] = '\0';
    break;
   }
  }
  int pos1 = ELFHash(buf)%maxn;
//  printf("我们在找%s", buf);
//  printf("%s", BUFF[pos1]);
  if(BUFF[pos1].str != NULL){
//  	printf("找到目的地\n");
  	node = &BUFF[pos1];
   while(node){
//   	printf("要比较的字符串是%s\n", node->str);
    if(strcmp(node->str, buf) == 0){
//    	printf("我们找到%s和%s\n", buf, node->str);
     res++;
     break;
    }
    node = node->next;
   }
  }
//  buf[100] = {'\0'};
//memset(buf, '\0', 100);
 }
 printf("%d", res);
// while (fgets(buf,99,fp)!=NULL){
//  printf("%s", buf);
// }
 return 0;
}

说一下开发中遇到的问题,结构体的定义问题,文件一行一行读的写法,还有编译器要使用-std=c11的参数方能允许在for循环中定义整数i。最后重要的点在于要在内存中存储的值都要malloc,不能只复制一个指针(地址)到Node的str上去,要让str指向在堆中创建的字符串数组,这样在内存中会存有实体值,后面的比较值能按预期的完成操作(感谢胡同学给我指出和指导这点,否则我将永远陷入指针的漩涡中)。

标签:node,哈希,int,代码,C语言,str,printf,buf,BUFF
来源: https://www.cnblogs.com/tellw/p/13728033.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有