示例#1
0
/**
 * Main method to add an element to the tree. It calls itself recursively.
 *
 * @param entry The current entry used for classification.
 * @param element The element to instert.
 */
void CBspTree::insertElement(TBspEntry* entry, CGraphicElement* element)
{
  // Check if we have reached the smallest splitting size. If so add the element to the given entry,
  // otherwise recurse down.
  float width = entry->bounds.lower.x - entry->bounds.upper.x;
  float height = entry->bounds.lower.y - entry->bounds.upper.y;
  if (width <= FMinSize || height <= FMinSize)
    entry->elements.push_back(element);
  else
  {
    TClassification classification = classify(entry, element);

    if (classification == IS_LEFT || classification == IS_BOTH)
    {
      // Go down the left sub tree. Create it if not yet done.
      if (entry->left == NULL)
      {
        TBspEntry* newEntry = new TBspEntry();
        entry->left = newEntry;
        newEntry->isVertical = !entry->isVertical;
        newEntry->bounds = entry->bounds;
        if (entry->isVertical)
        {
          newEntry->bounds.lower.x = (newEntry->bounds.lower.x + newEntry->bounds.upper.x) / 2;
          newEntry->splitPoint = (newEntry->bounds.lower.y + newEntry->bounds.upper.y) / 2;
        }
        else
        {
          newEntry->bounds.lower.y = (newEntry->bounds.lower.y + newEntry->bounds.upper.y) / 2;
          newEntry->splitPoint = (newEntry->bounds.lower.x + newEntry->bounds.upper.x) / 2;
        };
      };
      insertElement(entry->left, element);
    };

    if (classification == IS_RIGHT || classification == IS_BOTH)
    {
      // Go down the right sub tree. Create it if not yet done.
      if (entry->right == NULL)
      {
        TBspEntry* newEntry = new TBspEntry();
        entry->right = newEntry;
        newEntry->isVertical = !entry->isVertical;
        newEntry->bounds = entry->bounds;
        if (entry->isVertical)
        {
          newEntry->bounds.upper.x = (newEntry->bounds.lower.x + newEntry->bounds.upper.x) / 2;
          newEntry->splitPoint = (newEntry->bounds.lower.y + newEntry->bounds.upper.y) / 2;
        }
        else
        {
          newEntry->bounds.upper.y = (newEntry->bounds.lower.y + newEntry->bounds.upper.y) / 2;
          newEntry->splitPoint = (newEntry->bounds.lower.x + newEntry->bounds.upper.x) / 2;
        };
      };

      insertElement(entry->right, element);
    };
  };
}
示例#2
0
int main(int argc, const char * argv[]) {
    int Sqlist[MAXSIZE];
    int len;
    int i;
    printf("input array:(like 12,13,14):");
    for (i = 0 ; i < 6 ; i++)
    {
        scanf("%d,",&Sqlist[i]);
    }
    len = 6;
    printf("\nThe spare length is : %d\n",MAXSIZE - len);
    insertElement(Sqlist, &len, 3, 88);
    for (i = 0 ; i < len ; i++)
    {
        printf("%d ",Sqlist[i]);
    }
    printf("\nThe spare length is : %d\n",MAXSIZE - len);
    insertElement(Sqlist, &len, 11, 0);
    DelElement(Sqlist, &len, 6);
    for (i = 0 ; i < len; i++) {
        printf("%d ",Sqlist[i]);
    }
    printf("\nThe spare length is %d\n",MAXSIZE - len);
    return 0;
}
示例#3
0
文件: player.c 项目: 96kpan/csc352
//inserts node into the BST
int insertElement(struct TreeNode *tempNode, char *inputName, int won, int lost){
    
    
    
    //traverse the left BST
    if(strcmp(inputName, tempNode->player.name) < 0){
        
        
        if(tempNode->left == NULL){
            struct TreeNode *insertNode = createNode(inputName);
            tempNode->left = insertNode;
            
            if(won == 1){
                tempNode->left->player.wins++;
            }
            else{
                tempNode->left->player.losses++;
            }
            
            return 0;
        }
        insertElement(tempNode->left, inputName, won,lost);
    }
    
    //traverse the right BST
    else if(strcmp(inputName, tempNode->player.name) > 0){
        
        if(tempNode->right == NULL){
            struct TreeNode *insertNode = createNode(inputName);
            tempNode->right = insertNode;
            
            if(won == 1){
                tempNode->right->player.wins++;
            }
            else{
                tempNode->right->player.losses++;
            }
            return 0;
        }
        insertElement(tempNode->right, inputName, won, lost);
    }
    
    //if inputName already exists
    else if(strcmp(inputName, tempNode->player.name) == 0){
        
        //if won
        if(won == 1){
            tempNode->player.wins++;
        }
        //if lost
        else{
            tempNode->player.losses++;
        }
    }
    
    return 0;
};
示例#4
0
void add_ifrs_to_local_state(int num_new_ifrs, unsigned long *new_ifrs, int write) {
  int *curIFRVar;
  int *maxIFRVar;
  unsigned long **myIFRVars;

  if (write) {
    curIFRVar = &curWIFRVar;
    maxIFRVar = &maxWIFRVar;
    myIFRVars = &myWIFRVars;
  } else {
    curIFRVar = &curRIFRVar;
    maxIFRVar = &maxRIFRVar;
    myIFRVars = &myRIFRVars;
  }

  /* Expand the array if necessary. */
  while (*curIFRVar + num_new_ifrs > *maxIFRVar) {
    *myIFRVars = (unsigned long *) realloc(*myIFRVars, 2 * (*maxIFRVar)
					   * sizeof(unsigned long));
    if (!(*myIFRVars)) {
      fprintf(stderr, "[IFRit] ERROR: Could not allocate more memory for weak monitors\n");
      exit(1);
    }
    *maxIFRVar = (*maxIFRVar) * 2;
  }

  /* Insert the IFRs into the array. */
  int v;
  for (v = 0; v < num_new_ifrs; v++){
    insertElement(*myIFRVars, *curIFRVar, new_ifrs[v]);
    *curIFRVar = (*curIFRVar) + 1;
    assertSorted(*myIFRVars, *curIFRVar);
  }
}
示例#5
0
QString PrivateStorage::saveData(const Jid &AStreamJid, const QDomElement &AElement)
{
	if (FStanzaProcessor && isOpen(AStreamJid) && !AElement.tagName().isEmpty() && !AElement.namespaceURI().isEmpty())
	{
		Stanza request(STANZA_KIND_IQ);
		request.setType(STANZA_TYPE_SET).setUniqueId();
		QDomElement elem = request.addElement("query",NS_JABBER_PRIVATE);
		elem.appendChild(AElement.cloneNode(true));
		if (FStanzaProcessor->sendStanzaRequest(this,AStreamJid,request,PRIVATE_STORAGE_TIMEOUT))
		{
			LOG_STRM_INFO(AStreamJid,QString("Private data save request sent, ns=%1, id=%2").arg(AElement.namespaceURI(),request.id()));
			if (FPreClosedStreams.contains(AStreamJid))
				notifyDataChanged(AStreamJid,AElement.tagName(),AElement.namespaceURI());
			FSaveRequests.insert(request.id(),insertElement(AStreamJid,AElement));
			return request.id();
		}
		else
		{
			LOG_STRM_WARNING(AStreamJid,QString("Failed to send private data save request, ns=%1").arg(AElement.namespaceURI()));
		}
	}
	else if (!isOpen(AStreamJid))
	{
		REPORT_ERROR("Failed to save private data: Storage is not opened");
	}
	else if (AElement.tagName().isEmpty() || AElement.namespaceURI().isEmpty())
	{
		REPORT_ERROR("Failed to save private data: Invalid data");
	}
	return QString::null;
}
示例#6
0
void resizeHashTable()
{
	//! reconstruct the hash table by (usually) doubling its size
	//! only call this when the current fill factor of your hash table > MAX_FILL_FACTOR

	//! careful, when resizing, the 'size' variable should be changed as well such that the 'hashFunction's distribution will work
	//! be double careful! all the elements which are already in the hash table have to  be RE-hashed! (explanation @ lab)
	char **auxTable;
	int i;

	auxTable = hashTable;
	size = size * 2;
	hashTable = (char**)malloc(sizeof(char*) * size);
	i = 0;
	while (i < size)
	{
		hashTable[i] = NULL;
		i++;
	}
	i = 0;
	while (i < size / 2)
	{
		if (auxTable[i])
			insertElement(auxTable[i]);
		i++;
	}
	free(auxTable);
}
示例#7
0
文件: main.c 项目: CodeR57/DSA-lab
int main()
{
    int N = _5000;

    char ** content = readFromFile(N);
    //printContentToConsole(content,N);

    initHashTable(N);
    int i, aux;
    int maxColl = 0;
    nrOfResize = 0;
    float avgColl= 1;

    for (i=0; i<N; i++)
    {
        if ((i % 20) ==0)
            printf("\nElement Collisions FillFactor\n\n");
        aux = insertElement(*(content+i));
        printf("%7d %10d", i, aux);
        if (maxColl < aux)
            maxColl = aux;
        printf(" %8.2f%% \n", 100*getFillFactor());
        avgColl=(float)((((float)(avgColl)*i)+(float)aux)/(float)(i+1));


    }
    printf("\nNumber of resizes: %d\n", nrOfResize);
    printf("\nMaximal number of collisions: %d\n", maxColl);
    printf("\nAverage number of collisions: %f\n", avgColl);
    return 0;
}
示例#8
0
/* Resize the hash table so that it cantains "new_size" buckets.
** "new_size" must be a power of 2.  The hash table might fail 
** to resize if sqlite3_malloc() fails.
*/
static void rehash(Hash *pH, int new_size){
  struct _ht *new_ht;            /* The new hash table */
  HashElem *elem, *next_elem;    /* For looping over existing elements */

#ifdef SQLITE_MALLOC_SOFT_LIMIT
  if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
    new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
  }
  if( new_size==pH->htsize ) return;
#endif

  /* There is a call to sqlite3_malloc() inside rehash(). If there is
  ** already an allocation at pH->ht, then if this malloc() fails it
  ** is benign (since failing to resize a hash table is a performance
  ** hit only, not a fatal error).
  */
  if( pH->htsize>0 ) sqlite3BeginBenignMalloc();
  new_ht = (struct _ht *)sqlite3MallocZero( new_size*sizeof(struct _ht) );
  if( pH->htsize>0 ) sqlite3EndBenignMalloc();

  if( new_ht==0 ) return;
  sqlite3_free(pH->ht);
  pH->ht = new_ht;
  pH->htsize = new_size;
  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
    int h = strHash(elem->pKey, elem->nKey) & (new_size-1);
    next_elem = elem->next;
    insertElement(pH, &new_ht[h], elem);
  }
}
int main()
{
    #define arraysize 5
    int array[arraysize]={0};
    int i,elementsize=1,position,j,element;
    
    printf("请输入5个整数:\n");
    scanf("%d",&array[0]);
    
    for(i=0;i<arraysize;i++)
    {
                            scanf("%d",&element);
                            position=findPosition(array,arraysize,elementsize,element);
                             
                            j=insertElement(array,arraysize,elementsize,position,element);
                            //加[]有问题
                            elementsize++;
                            
                            if(j==1)
                            {
                                    printf("\n成功插入\n");
                            }
                            
                            if(elementsize==5)
                            {
                                    printf("\n成功插入\n");
                            }   
    }
    for(i=0;i<arraysize;i++)
    {
                            printf("%d\t",array[i]);
    }
}
示例#10
0
QString PrivateStorage::removeData(const Jid &AStreamJid, const QString &ATagName, const QString &ANamespace)
{
	if (FStanzaProcessor && isOpen(AStreamJid) && !ATagName.isEmpty() && !ANamespace.isEmpty())
	{
		Stanza request(STANZA_KIND_IQ);
		request.setType(STANZA_TYPE_SET).setUniqueId();
		QDomElement elem = request.addElement("query",NS_JABBER_PRIVATE);
		elem = elem.appendChild(request.createElement(ATagName,ANamespace)).toElement();
		if (FStanzaProcessor->sendStanzaRequest(this,AStreamJid,request,PRIVATE_STORAGE_TIMEOUT))
		{
			LOG_STRM_INFO(AStreamJid,QString("Private data remove request sent, ns=%1, id=%2").arg(ANamespace,request.id()));
			QDomElement dataElem = getData(AStreamJid,ATagName,ANamespace);
			if (dataElem.isNull())
				dataElem = insertElement(AStreamJid,elem);
			if (FPreClosedStreams.contains(AStreamJid))
				notifyDataChanged(AStreamJid,ATagName,ANamespace);
			FRemoveRequests.insert(request.id(),dataElem);
			return request.id();
		}
		else
		{
			LOG_STRM_WARNING(AStreamJid,QString("Failed to send private data remove request, ns=%1").arg(ANamespace));
		}
	}
	else if (!isOpen(AStreamJid))
	{
		REPORT_ERROR("Failed to remove private data: Storage is not opened");
	}
	else if (ATagName.isEmpty() || ANamespace.isEmpty())
	{
		REPORT_ERROR("Failed to remove private data: Invalid params");
	}
	return QString::null;
}
示例#11
0
void resizeHashTable(int N)
{
    //! reconstruct the hash table by (usually) doubling its size
    //! only call this when the current fill factor of your hash table > MAX_FILL_FACTOR

    //! careful, when resizing, the 'size' variable should be changed as well such that the 'hashFunction's distribution will work
    //! be double careful! all the elements which are already in the hash table have to  be RE-hashed! (explanation @ lab)

    char ** newHash;
    int newSize = size * 2, i;

    nrOfResizes+=1;

    newHash = (char**) malloc (newSize * sizeof(char*));

    for(i=0; i<newSize; i++)
        newHash[i] = NULL;

    // redistribute the elements of the old hash into the new hash

    for(i=0; i<size; i++)
    {
        if(hashTable[i] != NULL)
            collisions[i] += insertElement(hashTable[i], newSize, newHash);
    }

    //delete the old hash
    deleteHashTable(hashTable, size);

    //continue adding new elements into the new hash

    hashTable = newHash;
    size = newSize;
}
示例#12
0
int main(void)
{
    Node *head;
    Node *p;
    int i, value;
    int len = 5;

    head = NULL;   
    p = head;
    for(i = 0; i < len; i++)
    {
        scanf("%d", &value);
        head = insertElement(head, value);
    }
    printf("Here\n");
    p = head;
    if(head == NULL)
        printf("Bad\n");

    while( p!= NULL)
    {
        printf("%d\n", p->element);
        p = p->next;
    }
    return 0;
}
示例#13
0
文件: hash.c 项目: luobende/gadgets
/* Insert an element into the hash table pH.  The key is pKey
** and the data is "data".
**
** If no element exists with a matching key, then a new
** element is created and NULL is returned.
**
** If another element already exists with the same key, then the
** new data replaces the old data and the old data is returned.
** The key is not copied in this instance.  If a malloc fails, then
** the new data is returned and the hash table is unchanged.
**
** If the "data" parameter to this function is NULL, then the
** element corresponding to "key" is removed from the hash table.
*/
void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data) {
    unsigned int h;       /* the hash of the key modulo hash table size */
    HashElem *elem;       /* Used to loop thru the element list */
    HashElem *new_elem;   /* New element added to the pH */

    assert( pH!=0 );
    assert( pKey!=0 );
    elem = findElementWithHash(pH,pKey,&h);
    if( elem ) {
        void *old_data = elem->data;
        if( data==0 ) {
            removeElementGivenHash(pH,elem,h);
        } else {
            elem->data = data;
            elem->pKey = pKey;
        }
        return old_data;
    }
    if( data==0 ) return 0;
    new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
    if( new_elem==0 ) return data;
    new_elem->pKey = pKey;
    new_elem->data = data;
    pH->count++;
    if( pH->count>=10 && pH->count > 2*pH->htsize ) {
        if( rehash(pH, pH->count*2) ) {
            assert( pH->htsize>0 );
            h = strHash(pKey) % pH->htsize;
        }
    }
    insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem);
    return 0;
}
示例#14
0
Status Poly::create(int length)
{
    int i;
    int value_coef;  //用来存放用户输入的系数
    int value_expn;  //用于输入指数

    for(i=0; i < length; i++)
    {
        LElemType e;
        printf("请输入第%d项的系数:", i+1);
        scanf("%d", &value_coef);
        printf("请输入第%d项x的指数:", i+1);
        scanf("%d", &value_expn);
        e.coef_x = value_coef;  //向新结点中放入值
        e.expn_x = value_expn;

        printf("请输入第%d项y的指数:", i+1);
        scanf("%d", &value_expn);
        e.coef_y = value_coef;  //向新结点中放入值
        e.expn_y = value_expn;

        //添加数据
        insertElement(i, e);
    }
    return OK;
}
示例#15
0
// Resize the hash table so that it cantains "new_size" buckets.
// The hash table might fail to resize if system_malloc() fails or if the new size is the same as the prior size.
// Return TRUE if the resize occurs and false if not.
static int rehash(Hash *pH, unsigned int newSize) {
	struct _hashTable *newHashTable;				// The new hash table
	HashElement *element, *nextElement;	// For looping over existing elements
#if SYSTEM_MALLOC_SOFTLIMIT > 0
	if (newSize*sizeof(struct _hashTable) > SYSTEM_MALLOC_SOFTLIMIT)
		newSize = SYSTEM_MALLOC_SOFTLIMIT/sizeof(struct _hashTable);
	if (newSize == pH->TableSize)
		return 0;
#endif
	// The inability to allocates space for a larger hash table is a performance hit but it is not a fatal error.  So mark the allocation as a benign.
	systemBeginBenignMalloc();
	newHashTable = (struct _hashTable *)systemMalloc(newSize*sizeof(struct _hashTable));
	systemEndBenignMalloc();
	if (newHashTable == 0)
		return 0;
	system_free(pH->Table);
	pH->Table = newHashTable;
	pH->TableSize = newSize = systemMallocSize(newHashTable)/sizeof(struct _hashTable);
	memset(newHashTable, 0, newSize*sizeof(struct _hashTable));
	for(element = pH->First, pH->First = 0; element; element = nextElement) {
		unsigned int h = strHash(element->pKey, element->nKey) % newSize;
		nextElement = element->Next;
		insertElement(pH, &newHashTable[h], element);
	}
	return 1;
}
示例#16
0
文件: hash.c 项目: 0x7678/owasp-igoat
/* Resize the hash table so that it cantains "new_size" buckets.
**
** The hash table might fail to resize if sqlite3_malloc() fails or
** if the new size is the same as the prior size.
** Return TRUE if the resize occurs and false if not.
*/
static int rehash(Hash *pH, unsigned int new_size){
  struct _ht *new_ht;            /* The new hash table */
  HashElem *elem, *next_elem;    /* For looping over existing elements */

#if SQLITE_MALLOC_SOFT_LIMIT>0
  if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
    new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
  }
  if( new_size==pH->htsize ) return 0;
#endif

  /* The inability to allocates space for a larger hash table is
  ** a performance hit but it is not a fatal error.  So mark the
  ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of 
  ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
  ** only zeroes the requested number of bytes whereas this module will
  ** use the actual amount of space allocated for the hash table (which
  ** may be larger than the requested amount).
  */
  sqlite3BeginBenignMalloc();
  new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
  sqlite3EndBenignMalloc();

  if( new_ht==0 ) return 0;
  sqlite3_free(pH->ht);
  pH->ht = new_ht;
  pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
  memset(new_ht, 0, new_size*sizeof(struct _ht));
  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
    unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
    next_elem = elem->next;
    insertElement(pH, &new_ht[h], elem);
  }
  return 1;
}
示例#17
0
/* Insert an element into the hash table pH.  The key is pKey,nKey
** and the data is "data".
**
** If no element exists with a matching key, then a new
** element is created.  A copy of the key is made if the copyKey
** flag is set.  NULL is returned.
**
** If another element already exists with the same key, then the
** new data replaces the old data and the old data is returned.
** The key is not copied in this instance.  If a malloc fails, then
** the new data is returned and the hash table is unchanged.
**
** If the "data" parameter to this function is NULL, then the
** element corresponding to "key" is removed from the hash table.
*/
void *sqlite3HashInsert(Hash *pH, const void *pKey, int nKey, void *data){
  int hraw;             /* Raw hash value of the key */
  int h;                /* the hash of the key modulo hash table size */
  HashElem *elem;       /* Used to loop thru the element list */
  HashElem *new_elem;   /* New element added to the pH */

  assert( pH!=0 );
  hraw = strHash(pKey, nKey);
  if( pH->htsize ){
    h = hraw % pH->htsize;
    elem = findElementGivenHash(pH,pKey,nKey,h);
    if( elem ){
      void *old_data = elem->data;
      if( data==0 ){
        removeElementGivenHash(pH,elem,h);
      }else{
        elem->data = data;
        if( !pH->copyKey ){
          elem->pKey = (void *)pKey;
        }
        assert(nKey==elem->nKey);
      }
      return old_data;
    }
  }
  if( data==0 ) return 0;
  new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
  if( new_elem==0 ) return data;
  if( pH->copyKey && pKey!=0 ){
    new_elem->pKey = sqlite3Malloc( nKey );
    if( new_elem->pKey==0 ){
      sqlite3_free(new_elem);
      return data;
    }
    memcpy((void*)new_elem->pKey, pKey, nKey);
  }else{
    new_elem->pKey = (void*)pKey;
  }
  new_elem->nKey = nKey;
  pH->count++;
  if( pH->htsize==0 ){
    rehash(pH, 128/sizeof(pH->ht[0]));
    if( pH->htsize==0 ){
      pH->count = 0;
      if( pH->copyKey ){
        sqlite3_free(new_elem->pKey);
      }
      sqlite3_free(new_elem);
      return data;
    }
  }
  if( pH->count > pH->htsize ){
    rehash(pH,pH->htsize*2);
  }
  assert( pH->htsize>0 );
  h = hraw % pH->htsize;
  insertElement(pH, &pH->ht[h], new_elem);
  new_elem->data = data;
  return 0;
}
示例#18
0
文件: hash.c 项目: 77songsong/sqlite3
/* Resize the hash table so that it cantains "new_size" buckets.
**
** The hash table might fail to resize if sqlite3_malloc() fails or
** if the new size is the same as the prior size.
** Return TRUE if the resize occurs and false if not.
*/
static int rehash(Hash *pH, unsigned int new_size){
  struct _ht *new_ht;            /* The new hash table */
  HashElem *elem, *next_elem;    /* For looping over existing elements */

#if SQLITE_MALLOC_SOFT_LIMIT>0
  if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
    new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
  }
  if( new_size==pH->htsize ) return 0;
#endif

  /* The inability to allocates space for a larger hash table is
  ** a performance hit but it is not a fatal error.  So mark the
  ** allocation as a benign.
  */
  sqlite3BeginBenignMalloc();
  new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
  sqlite3EndBenignMalloc();

  if( new_ht==0 ) return 0;
  sqlite3_free(pH->ht);
  pH->ht = new_ht;
  pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
  memset(new_ht, 0, new_size*sizeof(struct _ht));
  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
    unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
    next_elem = elem->next;
    insertElement(pH, &new_ht[h], elem);
  }
  return 1;
}
void UndoInsertCommand::redo()
{
    if(_firstShot) {
        _firstShot = false ;
    } else {
        insertElement();
    }
}
int main()
{
	for (int i = 0; i < 4; i++)
	{
		insertElement(test[i].array, test[i].length, test[i].element);
		checkResult(test[i].expected_array, test[i].length, test[i].array);
	}
}
示例#21
0
/* Insert an element into the hash table pH.  The key is pKey,nKey
** and the data is "data".
**
** If no element exists with a matching key, then a new
** element is created.  A copy of the key is made if the copyKey
** flag is set.  NULL is returned.
**
** If another element already exists with the same key, then the
** new data replaces the old data and the old data is returned.
** The key is not copied in this instance.  If a malloc fails, then
** the new data is returned and the hash table is unchanged.
**
** If the "data" parameter to this function is NULL, then the
** element corresponding to "key" is removed from the hash table.
*/
void * HashInsert(
  Hash *pH,        /* The hash table to insert into */
  const void *pKey,    /* The key */
  int nKey,            /* Number of bytes in the key */
  void *data           /* The data */
){
  int hraw;                 /* Raw hash value of the key */
  int h;                    /* the hash of the key modulo hash table size */
  HashElem *elem;       /* Used to loop thru the element list */
  HashElem *new_elem;   /* New element added to the pH */
  
  assert( pH!=0 );
  hraw = binHash(pKey, nKey);
  assert( (pH->htsize & (pH->htsize-1))==0 );
  h = hraw & (pH->htsize-1);
  elem = findElementGivenHash(pH,pKey,nKey,h);
  if( elem ){
    void *old_data = elem->data;
    if( data==0 ){
      removeElementGivenHash(pH,elem,h);
    }else{
      elem->data = data;
    }
    return old_data;
  }
  if( data==0 ) return 0;
  new_elem = (HashElem*)pH->xMalloc( sizeof(HashElem) );
  if( new_elem==0 ) return data;
  if( pH->copyKey && pKey!=0 ){
    new_elem->pKey = pH->xMalloc( nKey );
    if( new_elem->pKey==0 ){
      pH->xFree(new_elem);
      return data;
    }
    memcpy((void*)new_elem->pKey, pKey, nKey);
  }else{
    new_elem->pKey = (void*)pKey;
  }
  new_elem->nKey = nKey;
  pH->count++;
  if( pH->htsize==0 ){
    rehash(pH,8);
    if( pH->htsize==0 ){
      pH->count = 0;
      pH->xFree(new_elem);
      return data;
    }
  }
  if( pH->count > pH->htsize ){
    rehash(pH,pH->htsize*2);
  }
  assert( pH->htsize>0 );
  assert( (pH->htsize & (pH->htsize-1))==0 );
  h = hraw & (pH->htsize-1);
  insertElement(pH, &pH->ht[h], new_elem);
  new_elem->data = data;
  return 0;
}
示例#22
0
void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
  unsigned int h;       /* the hash of the key modulo hash table size */
  HashElem *elem;       /* Used to loop thru the element list */
  HashElem *new_elem;   /* New element added to the pH */

  assert( pH!=0 );
  assert( pKey!=0 );
  assert( nKey>=0 );
  if( pH->htsize ){
    h = strHash(pKey, nKey) % pH->htsize;/*如果pH的htsize成员变量不为0,即使用哈希表存放数据项那么使用 strHash 函数计算桶号h*/
  }else{
    h = 0;/*如果pH的htsize成员变量为0,那么h=0*/
  }
  elem = findElementGivenHash(pH,pKey,nKey,h);
  if( elem ){
    void *old_data = elem->data;
    if( data==0 ){
      removeElementGivenHash(pH,elem,h);
    }else{
      elem->data = data;
      elem->pKey = pKey;
      assert(nKey==elem->nKey);
    }
    return old_data;
  }
  if( data==0 ) return 0;
  new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
  if( new_elem==0 ) return data;
  new_elem->pKey = pKey;
  new_elem->nKey = nKey;
  new_elem->data = data;
  pH->count++;
  if( pH->count>=10 && pH->count > 2*pH->htsize ){
    if( rehash(pH, pH->count*2) ){
      assert( pH->htsize>0 );
      h = strHash(pKey, nKey) % pH->htsize;
    }
  }
  if( pH->ht ){
    insertElement(pH, &pH->ht[h], new_elem);
  }else{
    insertElement(pH, 0, new_elem);
  }
  return 0;
}
static void test_insertElement(){
	printf("test_insertElement()\n");
	
	int input1[] = {1};
	insertElement(input1, 1, 0, 0);
	assert(input1[0] == 0);

	int input2[] = {1,-1, 0};
	insertElement(input2, 3, 2, 1);
	assert(input2[0] == 1);
	assert(input2[1] == 2);
	assert(input2[2] == -1);

	insertElement(input2, 3, 3, 2);
	assert(input2[0] == 1);
	assert(input2[1] == 2);
	assert(input2[2] == 3);
}
示例#24
0
daeInt daeSTLDatabase::insertChildren( daeDocument *c, daeElement *element )
{
	daeElementRefArray era;
	element->getChildren( era );
	for ( unsigned int i = 0; i < era.getCount(); i++ ) {
		insertElement( c, era[i] );
	}
	return DAE_OK;
}
int main(){

	node_t *head1 = NULL;
		
	int len1 = 0;
	int len2 = 0;
	//insertElement(1,&head1);
	insertElement(2,&head1);
	insertElement(4,&head1);
	insertElement(2,&head1);
	insertElement(1,&head1);

	int mid = returnIndex(head1);
	
	checkPalindrome(&head1,mid);
	
	
	
	return 0;
}
示例#26
0
/* Insert an element into the hash table pH.  The key is pKey,nKey
** and the data is "data".
**
** If no element exists with a matching key, then a new
** element is created and NULL is returned.
**
** If another element already exists with the same key, then the
** new data replaces the old data and the old data is returned.
** The key is not copied in this instance.  If a malloc fails, then
** the new data is returned and the hash table is unchanged.
**
** If the "data" parameter to this function is NULL, then the
** element corresponding to "key" is removed from the hash table.
*/
void *systemHashInsert(Hash *pH, const char *pKey, int nKey, void *data) {
	unsigned int h; // the hash of the key modulo hash table size
	HashElement *element; // Used to loop thru the element list
	HashElement *newElement; // New element added to the pH
	assert(pH != 0);
	assert(pKey != 0);
	assert(nKey >= 0);
	h = (pH->Table ? strHash(pKey, nKey) % pH->TableSize : 0);
	element = findElementGivenHash(pH, pKey, nKey, h);
	if (element) {
		void *lastData = element->Data;
		if (data == 0)
			removeElementGivenHash(pH, element, h);
		else {
			element->Data = data;
			element->pKey = pKey;
			assert(nKey == elem->nKey);
		}
		return lastData;
	}
	if (data == 0)
		return 0;
	newElement = (HashElement*)systemMalloc(sizeof(HashElement));
	if (newElement == 0)
		return data;
	newElement->pKey = pKey;
	newElement->nKey = nKey;
	newElement->Data = data;
	pH->Count++;
	if ((pH->Count >= 10) && pH->Count > (2*pH->TableSize))
		if (rehash(pH, pH->Count*2)) {
			assert(pH->TableSize > 0);
			h = strHash(pKey, nKey) % pH->TableSize;
		}
	if (pH->Table)
		insertElement(pH, &pH->Table[h], newElement);
	else
		insertElement(pH, 0, newElement);
	return 0;
}
示例#27
0
void StringList::insert(string value)
{
    StringList* tmp = next;
    if (tmp && (tmp = tmp->find(value)))
    {
        tmp->counter++;
    }
    else
    {
        insertElement(value);
        current->counter = 1;
    }
}
示例#28
0
void PrivateStorage::stanzaRequestResult(const Jid &AStreamJid, const Stanza &AStanza)
{
	if (FSaveRequests.contains(AStanza.id()))
	{
		QDomElement dataElem = FSaveRequests.take(AStanza.id());
		if (AStanza.isResult())
		{
			LOG_STRM_INFO(AStreamJid,QString("Private data saved on server, ns=%1, id=%2").arg(dataElem.namespaceURI(),AStanza.id()));
			notifyDataChanged(AStreamJid,dataElem.tagName(),dataElem.namespaceURI());
		}
		else
		{
			LOG_STRM_WARNING(AStreamJid,QString("Private data saved in local storage, ns=%1, id=%2: %3").arg(dataElem.namespaceURI(),AStanza.id(),XmppStanzaError(AStanza).condition()));
		}
		saveOptionsElement(AStreamJid,dataElem);
		emit dataSaved(AStanza.id(),AStreamJid,dataElem);
	}
	else if (FLoadRequests.contains(AStanza.id()))
	{
		QDomElement dataElem; 
		QDomElement loadElem = FLoadRequests.take(AStanza.id());
		if (AStanza.isResult())
		{
			dataElem = AStanza.firstElement("query",NS_JABBER_PRIVATE).firstChildElement(loadElem.tagName());
			LOG_STRM_INFO(AStreamJid,QString("Private data loaded from server, ns=%1, id=%2").arg(loadElem.namespaceURI(),AStanza.id()));
		}
		else
		{
			LOG_STRM_WARNING(AStreamJid,QString("Private data loaded from local storage, ns=%1, id=%2: %3").arg(loadElem.namespaceURI(),AStanza.id(),XmppStanzaError(AStanza).condition()));
		}
		if (dataElem.isNull())
			dataElem = loadOptionsElement(AStreamJid,loadElem.tagName(),loadElem.namespaceURI());
		emit dataLoaded(AStanza.id(),AStreamJid,insertElement(AStreamJid,dataElem));
	}
	else if (FRemoveRequests.contains(AStanza.id()))
	{
		QDomElement dataElem = FRemoveRequests.take(AStanza.id());
		if (AStanza.isResult())
		{
			LOG_STRM_INFO(AStreamJid,QString("Private data removed from server, ns=%1, id=%2").arg(dataElem.namespaceURI(),AStanza.id()));
			notifyDataChanged(AStreamJid,dataElem.tagName(),dataElem.namespaceURI());
		}
		else
		{
			LOG_STRM_WARNING(AStreamJid,QString("Private data removed from local storage, ns=%1, id=%2: %3").arg(dataElem.namespaceURI(),AStanza.id(),XmppStanzaError(AStanza).condition()));
		}
		removeElement(AStreamJid,dataElem.tagName(),dataElem.namespaceURI());
		removeOptionsElement(AStreamJid,dataElem.tagName(),dataElem.namespaceURI());
		emit dataRemoved(AStanza.id(),AStreamJid,dataElem);
	}
}
示例#29
0
文件: main.c 项目: LorhanSohaky/Queue
int main(){
    Lol a,b,*z;
    GenericField *k;
    Queue *fila;

    strcpy(a.c,"CASA1");
    strcpy(b.c,"CASA2");
    a.v=10;
    b.v=20;

    fila=createQueue();
    insertElement(fila,&a,STRUCT1);
    insertElement(fila,&b,STRUCT1);
    do{
        z=(Lol *)getFieldValue(getElement(fila));
		if(z!=NULL){
        	printf("%d  %s\n",z->v,z->c);
		}
    }while(nextElement(fila)==0);
    clearQueue(fila);
    getchar();
    return 0;
}
int main(){

SeqList sl1;

sl1=createList();

Element e1={3,4},e2={5,6},e3={7,8},e4={9,10};

sl1=insertElement(e1,sl1);
sl1=insertElement(e2,sl1);
sl1=insertElement(e3,sl1);
sl1=insertElement(e4,sl1);
printf("%d\n",sl1.size);
printList(sl1);

Element erem={5,6};

sl1=deleteElement(erem,sl1);
	printf("%d\n",sl1.size);
printList(sl1);

return 0;
}