/* * @description:重建哈希表,即进行扩容 */ void RecreateHash(HashTable *H) { int i,count; ElemType *p,*elem; count = (*H).count; elem = (ElemType *) malloc (count * sizeof(ElemType)); if(!elem) exit(OVERFLOW); //将现在哈希表中的元素暂存到elem中 for(i = 0 ; i < m ; i++) if((*H).elem[i].key != NULLKEY) *elem = *((*H).elem + i); (*H).count = 0; (*H).sizeindex++; m = hashsize[(*H).sizeindex]; p = (ElemType *) realloc ((*H).elem, m * sizeof(ElemType)); if(!p) exit(OVERFLOW); (*H).elem = p; //初始化新哈希表中元素值 for(i = 0; i < m ; i++) (*H).elem[i].key = NULLKEY; //将元素插入到新的哈希表中 for(p = elem ; p < elem + count ; p++) InsertHash(H,(*p).key); }
int* twoSum(int* nums, int numSize, int target) { int i; int tableSize = numSize*2; int* TwoNum = (int*)malloc(sizeof(int)*2); if (TwoNum == NULL) { printf("malloc TwoSum error\n"); return NULL; } HashList* list = InitHashTable(tableSize); for (i = 0; i < numSize; i++) { int pos; pos = Hash(abs(nums[i]), tableSize); InsertHash(nums[i], i, pos, list); } for (i = 0; i < numSize; i++) { int subdata = target-nums[i]; int pos = Hash(abs(subdata), tableSize); HashNode node = FindNode(i, pos, subdata, list); if (node != NULL) { TwoNum[0] = i+1; TwoNum[1] = node->index+1; FreeHash(list, tableSize); return TwoNum; } } FreeHash(list, tableSize); return NULL; }
static void ReHash(struct WordList *WL) { unsigned long i = 0; ClearHash(&WL->Hash); FORWL(i, *WL) InsertHash(WL->Stack.Data[i], &WL->Hash); }
int main(int argc, const char* argv[]) { int i; int* addr = (int *) malloc(sizeof(int)); HashTable H; InitHashTable(&H); for (i = 0; i < 10; i++) { InsertHash(&H, i * 2); } int t = SearchHash(H, 12, addr); printf("%d\n", t); }
/** * @brief Create hash information from a array. * * @param itemNum Number of items in array. * @param pArray Pointer pointed to array which will create hash information. * @return Pointer to created hash information. */ HashInf *HashFromArray(int itemNum, char **pArray) { PrepareCryptTable(); HashInf *pHashInf = (HashInf *)malloc(sizeof(HashInf)); pHashInf->pHashTable = InitHashTable(itemNum * ZOOM_TIMES_PREVENT_CONFLICT); pHashInf->nTableSize = itemNum * ZOOM_TIMES_PREVENT_CONFLICT; // Add each string to hash table. for (int i=0; i<itemNum; ++i) { InsertHash(pArray[i], pHashInf->pHashTable, pHashInf->nTableSize); } return pHashInf; }
void main() { ElemType r[N]={{17,1},{60,2},{29,3},{38,4},{1,5},{2,6},{3,7},{4,8},{60,9},{13,10}}; HashTable h; int i,p; Status j; KeyType k; InitHashTable(&h); for(i=0;i<N-1;i++) { /* 插入前N-1个记录 */ j=InsertHash(&h,r[i]); if(j==DUPLICATE) printf("表中已有关键字为%d的记录,无法再插入记录(%d,%d)\n",r[i].key,r[i].key,r[i].ord); } printf("按哈希地址的顺序遍历哈希表:\n"); TraverseHash(h,print); printf("请输入待查找记录的关键字: "); scanf("%d",&k); j=Find(h,k,&p); if(j==SUCCESS) print(p,h.elem[p]); else printf("没找到\n"); j=InsertHash(&h,r[i]); /* 插入第N个记录 */ if(j==ERROR) /* 重建哈希表 */ j=InsertHash(&h,r[i]); /* 重建哈希表后重新插入第N个记录 */ printf("按哈希地址的顺序遍历重建后的哈希表:\n"); TraverseHash(h,print); printf("请输入待查找记录的关键字: "); scanf("%d",&k); j=Find(h,k,&p); if(j==SUCCESS) print(p,h.elem[p]); else printf("没找到\n"); DestroyHashTable(&h); }
/* * Add one more symbol. */ static orl_return do_orl_symbol( orl_symbol_handle o_symbol ) /***********************************************************/ { char * name; char * namecopy; name = ORLSymbolGetName( o_symbol ); if( !is_name_mangled( name ) ) { namecopy = DupStrMem( name ); InsertHash( hashtable, namecopy ); } return( ORL_OKAY ); }
HASHPTR Find_and_Insert_Hash (HASHPTR symbol_tbl[], int size, char symbol[] , int key) { HASHPTR hp; //printf("in find and insert!\n"); if (key == 0) key = keyvalue (symbol); //printf("key = %d\n",key); if ((hp = FindHash (symbol_tbl, size, symbol, key)) == NULL) { //printf( "i didnt find it\n"); hp=InsertHash(symbol_tbl,size,symbol,key); } return(hp); }
/** * @brief Create hash information from list. * * @param itemNum Number of items in array. * @param list Pointer pointed to list which will create hash information. * @param GetNextStr Method of how to get string from list. * @return Pointer to created hash information. */ HashInf *HashFromList(int itemNum, char *(GetNextStr)(void **), void *list) { char *str = NULL; int hashTableIndex; PrepareCryptTable(); HashInf *pHashInf = (HashInf *)malloc(sizeof(HashInf)); pHashInf->pHashTable = InitHashTable(itemNum * ZOOM_TIMES_PREVENT_CONFLICT); pHashInf->nTableSize = itemNum * ZOOM_TIMES_PREVENT_CONFLICT; // Get every string in list and add them to hash table. while(NULL != (str = (*GetNextStr)(&list))) { InsertHash(str, pHashInf->pHashTable, pHashInf->nTableSize); } return pHashInf; }
/* * Process output from the WLIB DLL. */ static int wlib_output( const char *text ) /****************************************/ { bool badness = false; if( ( strncmp( text, "Error!", 6 ) == 0 ) || ( strncmp( text, "Warning!", 8 ) == 0 ) ) { badness = true; } if( !badness ) { if( strchr( text, ' ' ) == NULL ) { InsertHash( hashtable, (void*)DupStrMem( (char*)text ) ); } return( 1 ); } else { Warning( "Message from WLIB DLL: %s", text ); return( 0 ); } }
BOOL InsertWord(const STRPTR Word, struct WordList *WL) { STRPTR WrdCpy; ULONG Len; if((WrdCpy = strdupx(Word, WALLBYTES))) { if(StkPush(WrdCpy, &WL->Stack)) { Len = strlen(Word); if(WL->MaxLen < Len) WL->MaxLen = Len; InsertHash(WrdCpy, &WL->Hash); return(TRUE); } free(WrdCpy); } return(FALSE); }
int InsertWord(const char *Word, struct WordList *WL) { char *WrdCpy; unsigned long Len; if ((WrdCpy = strdupx(Word, WALLBYTES))) { if (StkPush(WrdCpy, &WL->Stack)) { Len = strlen(Word); if (WL->MaxLen < Len) WL->MaxLen = Len; InsertHash(WrdCpy, &WL->Hash); return (TRUE); } free(WrdCpy); } return (FALSE); }
/** Loads a table file into memory and returns the handle @param filename Pointer to the string that contains the filename of the table to load @return A handle to a TBLINFO struct requried for TBL operations or NULL if an error occured @example TBLINFO tblfile; tblfile = TBL_LoadTable("mytable.tbl"); */ TBLINFO TBLAPICALL TBL_LoadTable(const char *filename) { TBLINFO tbl; FILE *fp; /* handle to file */ char buffer[80], hex[10]; char *p, cntlval; int linecount; uint32 value; int size, len, n; /* allocate memory */ tbl = (TBLINFO)malloc(sizeof(__tag_TBLINFO)); if(!tbl) { TBL_Error("Out of memory."); goto TBL_LoadTableError0; } memset(tbl,0,sizeof(__tag_TBLINFO)); /* allocate memory for each entries */ tbl->entry = (TBLENTRY *)malloc(sizeof(TBLENTRY) * hashsize); if(!tbl->entry) { TBL_Error("Out of memory."); goto TBL_LoadTableError1; } memset(tbl->entry,0,sizeof(TBLENTRY) * hashsize); /* allocate memory for hash tables */ tbl->hv = (TBLENTRY **)malloc(sizeof(TBLENTRY *) * hashsize); if(!tbl->hv) { TBL_Error("Out of memory."); goto TBL_LoadTableError1; } memset(tbl->hv,0,sizeof(TBLENTRY *) * hashsize); tbl->hs = (TBLENTRY **)malloc(sizeof(TBLENTRY *) * hashsize); if(!tbl->hs) { TBL_Error("Out of memory."); goto TBL_LoadTableError1; } memset(tbl->hs,0,sizeof(TBLENTRY *) * hashsize); tbl->nEntries = 0; /* open file for reading */ fp = fopen(filename,"r"); if(!fp) { TBL_Error("%s: File not found.",filename); goto TBL_LoadTableError1; } linecount = 0; /* Read one line from file */ while(fgets(buffer,80,fp) != NULL) { linecount++; /* increment line count */ p = buffer; while(isspace(*p) && *p) p++; if(!*p) continue; /* if is empty line then continue */ cntlval = *p; if(cntlval == '*' || cntlval == '/') { /* if is a newline value */ p++; /* read values */ for(n = 0; n < 8 && isxdigit(*p); n++) { hex[n] = *p; p++; } hex[n] = '\0'; /* clear to endof line */ while(*p && isspace(*p)) p++; if(*p) { TBL_Error("%s: Line %d: Junk after hex value.",filename,linecount); goto TBL_LoadTableError2; } /* convert the values */ value = strtoul(hex,NULL,16); size = n / 2; switch(cntlval) { case '*': p = "\n"; break; case '/': p = ""; break; default : TBL_Error("%s: Line %d: Internal error occured. Please report bug.",filename,linecount); goto TBL_LoadTableError2; } } else { /* the first token should be a hex digit */ if(!isxdigit(*p)) { TBL_Error("%s: Line %d: Expecting a value here.",filename,linecount); goto TBL_LoadTableError2; } for(n = 0; n < 8 && isxdigit(*p); n++) { hex[n] = *p; p++; } hex[n] = '\0'; size = n / 2; /* calculate size by the amount of digits */ value = strtoul(hex,NULL,16); /* convert to value */ /* scan next; expecting '=' sign */ if(*p != '=') { TBL_Error("%s: Line %d: Expecting '='.",filename,linecount); goto TBL_LoadTableError2; } p++; len = strlen(p); /* get length of remaining data */ if(p[len - 1] == '\n') { /* kill the new line if there is one */ len--; p[len] = '\0'; } } if(tbl->nEntries >= hashsize) { TBL_Error("%s: Table overflow.",filename); goto TBL_LoadTableError2; } /* test for duplicate value definitions */ if(TBL_GetString(tbl,value,size,NULL)) { TBL_Error("%s: Line %d: Duplicate definition for value `%X'.",filename,linecount,value); goto TBL_LoadTableError2; } /* add the entry to the table */ n = tbl->nEntries; tbl->entry[n].value = value; tbl->entry[n].size = size; tbl->entry[n].string = strdup(p); if(!tbl->entry[n].string) { TBL_Error("Out of memory."); goto TBL_LoadTableError2; } /* Insert it into the hash table */ if( InsertHash(tbl,&tbl->entry[n]) ) goto TBL_LoadTableError2; tbl->nEntries++; } fclose(fp); return tbl; TBL_LoadTableError2: fclose(fp); TBL_LoadTableError1: TBL_CloseTable(tbl); TBL_LoadTableError0: return NULL; }
/*------add_PO------------------------------------------------------- adds a PO gate at each primary output should be called before levelize() modified by Hyung K Lee 2/15/1991 --------------------------------------------------------------------*/ int addPOGates() //add_PO { //PO Gates only have 1 input from now on !! register int i, j; GATEPTR pGate, pNewPOGate, *pOutList; char strNewPOName[MAXSTRING]; for (i = 0; i < g_iNoPO; i++) { pGate = g_net[g_PrimaryOut[i]]; if ((pNewPOGate = g_net[g_iNoGate]) == NULL) { //ALWAYS Come Here !! ALLOCATE(pNewPOGate, GATETYPE, 1); } pNewPOGate->index = g_iNoGate; pNewPOGate->type = PO; pNewPOGate->inCount = 1; ALLOCATE(pNewPOGate->inList, GATEPTR, 1); pNewPOGate->inList[0] = pGate; pNewPOGate->outCount = 0; pNewPOGate->outList = NULL; #ifdef LEARNFLG pNewPOGate->plearn = NULL; #endif strcpy(strNewPOName, pGate->hash->symbol); strcat(strNewPOName, "_PO"); while ((pNewPOGate->hash = FindHash(pArrSymbolTable, HASHSIZE, strNewPOName, 0)) != NULL) { //Avoid name conflict strcat(strNewPOName, "_PO"); } if ((pNewPOGate->hash = InsertHash(pArrSymbolTable, HASHSIZE, strNewPOName, 0)) == NULL) { printFatalError(HASHERROR); } else { //ALWAYS Come Here !! pNewPOGate->hash->gate = pNewPOGate; } //////////////Memory Leak // pOutList = pGate->outList; // ALLOCATE(pGate->outList, GATEPTR, pGate->outCount + 1); // for (j = 0; j< pGate->outCount; j++) // pGate->outList[j] = pOutList[j]; /////////////////////////// GATEPTR *pTempOutList; pOutList = pGate->outList; ALLOCATE(pTempOutList, GATEPTR, pGate->outCount + 1); for (j = 0; j< pGate->outCount; j++) { pTempOutList[j] = pOutList[j]; } free(pGate->outList); // If not, then memory leak !! pGate->outList = pTempOutList; ////////////////////////////////// pGate->outList[pGate->outCount] = pNewPOGate; pGate->outCount += 1; g_PrimaryOut[i] = g_iNoGate; g_net[g_iNoGate++] = pNewPOGate; /* if(pOutList!=NULL) FREE(pOutList); */ } return(g_iNoPO); }
int CallAddr(IPAddress addr, short port, Socket *sock, double timeOut) { struct sockaddr_in server; /* remote host address */ Socket sd; int one = 1; int sock_opt_len = sizeof(int); double start; double end; double ltimeout; void (*was)(int); was = signal(SIGALRM, ConnectTimeOut); memset((char *)&server, 0, sizeof(server)); server.sin_addr.s_addr = addr; server.sin_family = AF_INET; server.sin_port = htons((u_short)port); sd = socket(AF_INET, SOCK_STREAM, 0); if(sd < 0) { *sock = NO_SOCKET; signal(SIGALRM, was); FAIL("CallAddr: cannot create socket to server\n"); } if(setsockopt(sd, SOL_SOCKET, SO_KEEPALIVE, (char *)&one, sock_opt_len) < 0) { WARN("CallAddr: keepalive option failed\n"); } if(setsockopt(sd, TcpProtoNumber(), TCP_NODELAY, (char *)&one, sock_opt_len) < 0) { WARN("CallAddr: couldn't set NODELAY flag\n"); } ltimeout = ConnTimeOut(addr); if(ltimeout == 0.0) ltimeout = timeOut; SetRealTimer((unsigned int)ltimeout); start = CurrentTime(); if(connect(sd, (struct sockaddr *)&server, sizeof(server)) < 0) { shutdown(sd, 2); close(sd); *sock = NO_SOCKET; RESETREALTIMER; if(errno == EINTR) { /* this was a timeout */ end = CurrentTime(); InsertHashAddr(addr); SetConnTimeOut(addr, end - start, 1); } signal(SIGALRM,was); FAIL("CallAddr: connect failed\n"); } end = CurrentTime(); RESETREALTIMER; *sock = sd; if (debug > 0) { DDEBUG2("CallAddr: connected socket %d to %s\n", sd, PeerName(sd)); } FD_SET(sd, &connectedSockets); InsertHash(sd); SetConnTimeOut(addr, end - start, 0); SetPktTimeOut(sd, end - start, 0); signal(SIGALRM,was); return(1); }
boolean InsertList(pointer object, List l) { ListElem *t; ListElem *oldT; t=(ListElem *)malloc(sizeof(ListElem)); if(!t) { Error("InsertList, unable to allocate ListElem\n", NO_EXIT); return FALSE; } t->obj=object; if(l->hash) InsertHash(t, l->hash); switch(l->type) { case ORDERED: FindLessObj(object,l); t->next=l->C; if(l->C) /* insert before l->C */ { t->prev=l->C->prev; if(l->C->prev) l->C->prev->next=t; /* normal case */ else l->T=t; /* l->C was Tail */ l->C->prev=t; } else /* insert in Head */ { t->prev=l->H; if(l->H) l->H->next=t; /* list not empty */ else l->T=t; /* empty list, modify Tail */ l->H=t; } t->next=l->C; break; case CIRCULAR: if(l->C) /* insert before l->C */ { t->next=l->C; /* normal case */ t->prev=l->C->prev; l->C->prev->next=t; l->C->prev=t; l->T=l->H->next; /* Adjust Head and Tail. */ l->C=t; /* Move l->C to Last inserted */ } else if(l->nobject==0) /* List was empty */ { l->C=t; t->next=t; t->prev=t; l->H=t; l->T=t; } else /* l->C==NULL and Not Empty List */ ErrorFALSE("InsertList, NULL CurrList in a CIRCULAR list.\n") break; case FIFO: case LIFO: oldT=l->T; l->T=t; l->T->next=oldT; l->T->prev=NULL; if(oldT==NULL) l->H=t; /* If empty list init head of list */ else oldT->prev=t; } l->nobject++; return TRUE; }