Esempio n. 1
0
/*
 *
 *  Helper functions
 *
 */
int populate_list(SortedListPtr s, int type, int len, int iargs[], double dargs[],char*sargs[]){

    int i;
    if(type == INT){
        for(i = 0; i < len; i++){
            if(SLInsert(s,&(iargs[i])) == 0){
                return 0;
            }
        }
    }else if (type == DOUBLE){
        for(i = 0; i < len; i++){
            if(SLInsert(s,&(dargs[i])) == 0){
                return 0;
            }
        }
    }else if(type==STRING){
        printf("STRINGS\n");
        for(i = 0; i < len; i++){
            printf("Inserting %s\n", sargs[i]);

            if(SLInsert(s,sargs[i]) == 0){
                return 0;
            }
        }
    }

    return 1;

}
void add_record(char *word, char *filename)
{
  struct Record *r;

  int record_id = djb2((unsigned char *) word);

  HASH_FIND_INT(records, &record_id, r);
  // linear probing to resolve collisions
  while (r != NULL) {
    // found word
    if (strcmp(r->word, word) == 0) {
      break;
    }

    record_id++;
    HASH_FIND_INT(records, &record_id, r);
  }

  if (r == NULL) {
    // found empty spot, proceed to add
    r = (struct Record *)malloc(sizeof(struct Record));
    r->id = record_id;
    r->word = word;
    r->filenames = SLCreate(compareStrings, destroyStrings);
    SLInsert(r->filenames, filename);

    HASH_ADD_INT(records, id, r);
  } else {
    SLInsert(r->filenames, filename);
  }
}
Esempio n. 3
0
void ht_merge(SortedListPtr list, const char* filepath, HashTable *hashtable, SortedListPtr wordlist) {
	FileCountPair *fcp;
	WordCountPair *wcp;
	SortedListIteratorPtr iterator;
	SortedListIteratorPtr mainListIterator;
	char *word;
	WordListPair *wlp;

	iterator = SLCreateIterator(wordlist);
	
	while ((word = SLNextItem(iterator)) != NULL) {
		mainListIterator = SLCreateIterator(list);
		wcp = ht_get(hashtable, word);
		fcp = malloc(sizeof(FileCountPair));
		fcp->filepath = filepath;
		fcp->count = wcp->count;
		while ((wlp = SLNextItem(mainListIterator)) != NULL) {
			if (strcmp(wlp->word, word) == 0) {
				break;
			}
		}
		if (wlp == NULL) {	//the word is not already in the main list
			SortedListPtr newlist = SLCreate(&compareFileCounts);
			SLInsert(newlist, fcp);
			wlp = malloc(sizeof(WordListPair));
			wlp->word = word;
			wlp->list = newlist;
			SLInsert(list, wlp);
		} else {
			SLInsert(wlp->list, fcp);
		}
		SLDestroyIterator(mainListIterator);
	}
	SLDestroyIterator(iterator);
}
Esempio n. 4
0
int addWord(char * word, char * filename){
    //intialisation
    WordCount fileToAdd;
    fileToAdd = (WordCount)malloc(sizeof(WordCount));
    fileToAdd->filename = (char*)malloc((sizeof(char)*100));
    fileToAdd->count = 1;
    fileToAdd->filename = filename;
    ll word = (ll)malloc(sizeof(ll));
    word->word = (char*)malloc((sizeof(char)*100));
    word->word = word;
    
    //need to look at sorted list
    ll wordexists;
    wordexists = (ll) SLFindNode(wordList, word);
    
    //if exists
    
    if(wordexists != NULL){
        printf("word %s exists\n", word);
        SortedListIteratorPtr iter;
        iter =  SLCreateIterator(wordexists->file);
        void *object =  NULL;
        while((object = SLNextItem(iter))){
            WordCount file;
            file = object;
            
            if(compareCounts(file, object) == 0){
                file->count++;
                break;
            }
            //addWord(file->file->filename);
        }
        SLDestroyIterator(iter);
        
        if(object == NULL){ //does not found, add!!
            SLInsert(wordexists->file, fileToAdd); //adding
            //free
            free(word->word);
            free(word);
            return 1;
        }
        else{
            //free everything
            printf("error when adding word\n");
            free(fileToAdd->filename);
            free(fileToAdd);
            free(word->word);
            free(word);
        }
        return 0;
    }
    else{ //file not found
        word->file = SLCreate(compareCounts);
        SLInsert(word->file,fileToAdd);
        SLInsert(wordList, word);
        return 1;
    }
}
Esempio n. 5
0
/* Given a line of file stats, create a Sorted List of file stats
 * and return it
 * 
 */
 SortedListPtr buildFileStatsList(char *line)
 {
	 SortedListPtr newList = SLCreate(*compareStatsByFrequency);
	 //tokenize by spaces
	 char *result = NULL;
	 result = strtok(line, " ");
	 //tokenize until there are no more spaces
	 char *filename = NULL;
	 while(result != NULL)
	 {
		 int testNum = atoi(result);
		 if(testNum == 0) //It must be a file name then
		 {
			 filename = result;
		 }
		 else
		 {
			 if(filename != NULL)
			 {
				 StatsPtr newStatsStruct = createStatsStruct(filename);
				 newStatsStruct->frequency = testNum;
				 int insert = SLInsert(newList, newStatsStruct);
				 if(insert == 0) //Need to force it in the list
				 {
					 SLInsertIndex(newList, newStatsStruct);
				 }
			 }
		 }
		 result = strtok(NULL, " ");
	 }
	 return newList;
 }
Esempio n. 6
0
/*
test 7:
1. create list with compare and destroy functions
2. check SLInsert, add 1, 2, 3, 4, 5, SLRemove
3. create list iterate
4. check SLGetItem, SLNextItem
5. destroy list iterator
6. destroy list
*/
void test7(){
	SortedListPtr list = SLCreate(compare, destroy);
	SortedListIteratorPtr iter;
	int i;
	int* value;

	for (i = 1; i <= 5; i++)
	{
		value = (int*)malloc(sizeof(int));	
		*value = i;
		SLInsert(list, (void*)value);
	}

	iter = SLCreateIterator(list);
	i = SLRemove(list, value);
	printf("SLRemove 5 returned %d\n", i);

	i = SLRemove(list, value);
	printf("SLRemove 5 returned %d\n", i);

	value = (int*)SLGetItem(iter);
	while (value != NULL)
	{
		printf("Value = %d\n", *value);		
		value = (int*)SLNextItem(iter);		
	}	


	SLDestroy(list);
	SLDestroyIterator(iter);

	printf("Test 7 completed\n");
}
Esempio n. 7
0
/*
test 6:
1. Do the test 5 with SLNextItem over list
*/
void test6(){
	SortedListPtr list = SLCreate(compare, destroy);
	SortedListIteratorPtr iter;
	int i;
	int* value;

	for (i = 1; i <= 5; i++)
	{
		value = (int*)malloc(sizeof(int));	
		*value = i;
		SLInsert(list, (void*)value);
	}

	iter = SLCreateIterator(list);
	
	value = (int*)SLGetItem(iter);
	while (value != NULL)
	{
		printf("Value = %d\n", *value);		
		value = (int*)SLNextItem(iter);		
	}	

	value = (int*)SLNextItem(iter);		
	if (value != NULL)
	{
		printf("Over end of list, must be null\n");
		exit(0);
	}

	SLDestroy(list);
	SLDestroyIterator(iter);

	printf("Test 6 completed\n");
}
Esempio n. 8
0
int main(int argc, char **argv) {
  /* int i7,i5,i3,i4; */
  /* double d1, d2, d3, d4, d5; */
  char *s1, *s2, *s3, *s4, *s5;

  SortedListPtr sl;
  SortedListIteratorPtr slip;

  sl = SLCreate(compareInts);

  s1 = "Hello";
  s2 = "World";
  s3 = "Dawgs";
  s4 = "Tacos";
  s5 = "Zebra";

  SLInsert(sl, s1); // => ['HELLO']
  printListString(sl);
  SLInsert(sl, s2); // => ['WORLD', 'HELLO']
  printListString(sl);
  SLInsert(sl, s3); // => ['WORLD', 'HELLO', 'DOGS']
  printListString(sl);
  SLInsert(sl, s4); // => ['WORLD', 'HELLO', 'DOGS']
  printListString(sl);
  SLInsert(sl, s5); // => ['ZZZ', 'WORLD', 'HELLO', 'DOGS']
  printListString(sl);
  SLRemove(sl, s2); // => ['ZZZ', 'HELLO', 'DOGS']
  printListString(sl);

  slip = SLCreateIterator(sl);

  printf("------------------------------\n");

  printf("%s\n", (char*)SLNextItem(slip));
  SLRemove(sl, s1);
  printf("%s\n", (char*)SLNextItem(slip));
  printListString(sl);
  printf("%s\n", (char*)SLNextItem(slip));

  SLDestroyIterator(slip);
  SLDestroy(sl);

  return 0;
}
Esempio n. 9
0
/*
 *
 *  Helper functions
 *
 */
int populate_list(SortedListPtr s, int type, int len, int iargs[], double dargs[],char*sargs[], TestStruct strtargs[]){
    
    
    int i;
    if(type == INT){
        for(i = 0; i < len; i++){
            int *toinsert = (int*)malloc(sizeof(int));
            *toinsert = iargs[i];
            if(SLInsert(s,toinsert) == 0){
                return 0;
            }
        }
    }else if (type == DOUBLE){
        for(i = 0; i < len; i++){
            double *toinsert = (double*)malloc(sizeof(double));
            *toinsert = dargs[i];
            if(SLInsert(s,toinsert) == 0){
                return 0;
            }
        }
    }else if(type==STRING){
        for(i = 0; i < len; i++){
            char *toinsert = (char*)malloc(strlen(sargs[i])+1);
            toinsert[strlen(sargs[i])] = 0;
            strcpy(toinsert,sargs[i]);
            
            if(SLInsert(s,toinsert) == 0){
                return 0;
            }
        }
    }else if (type == STRUCT){
        for(i = 0; i < len; i++){
            TestStruct *toinsert = (TestStruct*)malloc(sizeof(TestStruct));
            toinsert->field = (strtargs[i]).field;
            if(SLInsert(s,toinsert) == 0){
                return 0;
            }
        }
    }
    
    return 1;
    
}
Esempio n. 10
0
SortedListPtr inputToLinkedList(char* tokenInput)
{
	//create new list
	SortedListPtr inputList = SLCreate(*compareStrings);
	//add words to linked list until the tokenstream is null
	while(tokenInput != NULL)
	{
		SLInsert(inputList, tokenInput);
		tokenInput = strtok(NULL, " ");
	}
	return inputList;
}
Esempio n. 11
0
/* Insert all file names from a given word's node into a given list
 * 
 */ 
void insertAllFilenames(SortedListPtr list, SLNode word)
{
	WordPtr actualWord = (WordPtr)word->value;
	SortedListIteratorPtr filenameIter = SLCreateIterator(actualWord->filestats);
	do
	{
		StatsPtr curStat = filenameIter->curNode->value;
		char *word = curStat->filename;
		SLInsert(list, word);
	}while(SLNextItem(filenameIter) != NULL);
	SLDestroyIterator(filenameIter);
}
Esempio n. 12
0
void insert(NNodePtr item){
    HashBucket * current_token;
    char * KEY = item->key;
    HASH_FIND_STR(tokens, KEY , current_token);
    
//    printf("KEY: %s\n", KEY);
    if(current_token==NULL){
        current_token = (HashBucket*)malloc(sizeof(HashBucket));
        current_token->name = item->key;
        
        
        CompareFuncT c = compareInts;
        SortedListPtr temp = SLCreate(c);
        int * one = malloc(sizeof(int));
        *one  = 1;
        
        int success;
        success = SLInsert(temp, (void*)one, item->filename);
        current_token->list = temp;
        HASH_ADD_STR(tokens, name, current_token);
        
        //        free(item);
    }
    else{
//        printf("Entered process\n");
        SortedListPtr temp = current_token->list;
        int success = 0;
        int * one = malloc(sizeof(int));
        *one  = 1;
        
        void*zone = (void*)one;
        success = SLInsert(temp, zone, item->filename);
        current_token->list = temp;
        HASH_DEL(tokens, current_token);
        HASH_ADD_STR(tokens, name, current_token);
        //free(item);
    }
    
    return;
}
Esempio n. 13
0
/*
	process Token will add the (token, filename) tuple to the TokenList object.
		Duplicate (token, filename) will increment frequency.
		New tuples will create new objects to be added to the nested sorted-lists.

	@param word 	: Token to be added
	@param filename : Filename associated with word
*/
void processToken(char* word, char* filename)
{
	Token 		*searchToken;
	fileRecord 	*searchRecord;
	Token   	*newToken 	= malloc(sizeof(Token));
	fileRecord  *newRecord 	= malloc(sizeof(fileRecord));
	
	if (newRecord == NULL || newToken == NULL) {
		fprintf(stderr, "errno %d\n", errno);
		fprintf(stderr, "mesg: %s\n", strerror(errno));
		exit(-1);
	}

	newToken->word    	 	= word;
	newToken->fileList   	= NULL;
	newRecord->filename 	= copyFileName(filename);
	newRecord->frequency	= 1;

	if( (searchToken = SLSearch(TokenList, newToken, compareRecordName)) != NULL ){

		if( (searchRecord = SLSearch(searchToken->fileList, newRecord, compareRecordName)) != NULL ){
			
			int freq = searchRecord->frequency;
			newRecord->frequency = freq+1;
			SLInsert(searchToken->fileList, newRecord);
			SLRemove(searchToken->fileList, searchRecord);			

		}
		else{
			SLInsert(searchToken->fileList, newRecord);
		}
		destroyTokenStruct(newToken);
	}
	else{
		newToken->fileList = SLCreate(compareRecordStructs, destroyFileRecord);
		SLInsert(newToken->fileList, newRecord);
		SLInsert(TokenList, newToken);
	}

}
Esempio n. 14
0
File: main.c Progetto: CS214/p2ll
int main(int argc, char** argv){

	//***************** STRING TEST ***********************
	int i;
	const char* stringList[] = {"Hey", "Boy", "Zeus", "world", " ", "blah", " zzz", "aaa"};

	char* stringPtr = (char*) malloc(sizeof(stringList));

	SortedListPtr stringsl = SLCreate(compareStrings, NULL);
	/*
	for(i=0; i<(sizeof(stringList)/sizeof(stringList[0])); i++){
		stringPtr = (char*) stringList[i];
		SLInsert(stringsl, stringPtr);
	}
	*/
	SortedListIteratorPtr stringiterator2 = SLCreateIterator(stringsl);
	SLNextItem(stringiterator2);

	SLInsert(stringsl, "f");
	SLInsert(stringsl, "d");
	SLInsert(stringsl, "b");
	//SLRemove(stringsl, "Apple");
	
	
	
	
	SortedListIteratorPtr stringiterator = SLCreateIterator(stringsl);

	while((stringPtr = (char*) SLNextItem(stringiterator)) != NULL){
		printf("%s\n", stringPtr);
	}

	//cleans mess
	free(stringPtr);
	SLDestroy(stringsl);
	SLDestroyIterator(stringiterator);
}
Esempio n. 15
0
int ht_update(HashTable *hashtable, char *word, SortedListPtr wordlist) {

	unsigned int index;
	LinkedList *bucket;
	LinkedList *prev;
	LinkedList *newnode;
	WordCountPair *wcp;

	if (hashtable == NULL) {
		return 0;
	}
	if (word == NULL) {
		return 0;
	}

	index = hash(word) % hashtable->size;
	bucket = hashtable->table[index];
	prev = bucket;

	while (bucket != NULL && strcmp((bucket->wcp)->word, word) != 0) {
		prev = bucket;
		bucket = bucket->next;
	}
	if (bucket == NULL) {
		newnode = malloc(sizeof(LinkedList));
		wcp = malloc(sizeof(WordCountPair));
		wcp->word = word;
		wcp->count = 1;
		newnode->wcp = wcp;
		newnode->next = NULL;
		if (prev == NULL) {
			hashtable->table[index] = newnode;
		} else {
			prev->next = newnode;
		}
		SLInsert(wordlist, word);
		return 1;
	}

	(bucket->wcp)->count++;
	return 1;

}
Esempio n. 16
0
/* Given the name of a file exported from indexer, parse it back into
 * the linked list form.
 * 
 */ 
SortedListPtr parseFileToList(char *filename)
{
	FILE *fp = fopen(filename,"r");
	if(fp == NULL)
	{
		printf("Unable to open file %s\n",filename);
		return NULL;
	}
	SortedListPtr newList = SLCreate(*compareWordStruct);
	WordPtr curWord = NULL;
	char line[128];
	while(fgets(line,128,fp) != NULL)
	{
		//Trim the newline character.
		if(strlen(line) > 0)
		{
			line[strlen(line)-1] = '\0';
			//printf("Input trimmed.\n");
		}
		//Classify the type of line.
		enum lineType curLine = classifyLine(line);
		//printf("Line type: %d\n",curLine);
		switch(curLine)
		{
			case WordLine:
				//Extract the word from the line.
				curWord = extractWord(line);
				//printf("Inserting new word into list.\n");
				SLInsert(newList, curWord);
				break;
			case FileStatsLine:
				//Parse the line
				//Add the file stats to curWord's filestatslist
				curWord->filestats = buildFileStatsList(line);
				break;
			case Throwaway:
				//Do nothing I guess.
				break;
		}
	}
	fclose(fp);
	return newList;
}
Esempio n. 17
0
SortedListPtr searchOr(SortedListPtr indexList, SortedListPtr inputList)
{
	//need a result list
	SortedListPtr result = SLCreate(*compareStrings);
	//need to iterate through the inputList to check the words in the indexList
	SortedListIteratorPtr inputIterator = SLCreateIterator(inputList);
	do
	{
		SLNode inputListPtr = inputIterator->curNode;
		char* inputListWord = (char*)inputListPtr->value;
		//need to iterate through the indexListIterator for each item of inputList
		SortedListIteratorPtr indexListIterator = SLCreateIterator(indexList);
		do
		{
			//compare the word in the indexed list to the input list to see if they match
			SLNode indexListPtr = indexListIterator->curNode;
			WordPtr indexWord = (WordPtr) indexListPtr->value;
			int compareWords = strcmp(indexWord->wordArray, inputListWord);
			if(compareWords == 0)
			{
				//extract the filelist for the word
				SortedListPtr filePtr = indexWord->filestats;
				SortedListIteratorPtr fileIterator = SLCreateIterator(filePtr);
				//add the word to the result list
				do
				{
					SLNode fileHead = (SLNode)filePtr->headOfList;
					StatsPtr fileNamesPtr = (StatsPtr)fileHead->value;
					char* filenameToAdd = fileNamesPtr->filename;
					SLInsert(result, filenameToAdd);
				}while (SLNextItem(fileIterator) != NULL);
				SLDestroyIterator(fileIterator);
			} 
		} while (SLNextItem(indexListIterator) != NULL);
		SLDestroyIterator(indexListIterator);
	} while(SLNextItem(inputIterator) != NULL);
	SLDestroyIterator(inputIterator);
	return result;
}
Esempio n. 18
0
/* Given two lists of file names, return a list of file names that
 * is in both lists.
 */ 
SortedListPtr findCommonElements(SortedListPtr firstList, SortedListPtr secondList)
{
	SortedListPtr commonElements = SLCreate(*compareStrings);
	SortedListIteratorPtr outsideIter = SLCreateIterator(firstList);
	do
	{
		//printf("Grabbing outside node.\n");
		SLNode outsideNode = outsideIter->curNode;
		SortedListIteratorPtr insideIter = SLCreateIterator(secondList);
		do
		{
			//For every element in the second list, compare it to whatever my outsideIter is pointing to.
			SLNode insideNode = insideIter->curNode;
			//printf("Attempting to compare file stats by file name\n");
			//int compareVal = compareStatsByFilename(outsideNode->value, insideNode->value);
			if(outsideNode == NULL || insideNode == NULL || outsideNode->value == NULL || insideNode->value == NULL)
			{
				SLDestroyIterator(insideIter);
				SLDestroyIterator(outsideIter);
				SLDestroy(commonElements);
				//printf("Returning from findcommonelements because something is null.\n");
				return NULL;
			}
			int compareVal = strcmp(outsideNode->value, insideNode->value);
			//printf("Compareval = %d\n",compareVal);
			if(compareVal == 0) //Same file name, add it to the results list
			{
				//Theyre the same, so I can just add the outside one
				char* outsideStats = outsideNode->value;
				//printf("Found common element: %s\n", outsideStats);
				SLInsert(commonElements, outsideStats);
			}
		}while(SLNextItem(insideIter) != NULL);
		SLDestroyIterator(insideIter);		
	}while(SLNextItem(outsideIter) != NULL);
	SLDestroyIterator(outsideIter);
	return commonElements;
}
Esempio n. 19
0
/*
test 4:
1. create list with compare and destroy functions
2. check SLInsert, add 1, 2, 3, 4, 5
3. create list iterate
4. check SLGetItem
5. destroy list iterator
6. destroy list
*/
void test4(){
	SortedListPtr list = SLCreate(compare, destroy);
	SortedListIteratorPtr iter;
	int i;
	int* value;

	for (i = 1; i <= 5; i++)
	{
		value = (int*)malloc(sizeof(int));	
		*value = i;
		SLInsert(list, (void*)value);
	}

	iter = SLCreateIterator(list);

	value = (int*)SLGetItem(iter);
	printf("Value = %d\n", *value);

	SLDestroy(list);
	SLDestroyIterator(iter);

	printf("Test 4 completed\n");
}
Esempio n. 20
0
int main()
{
  SortedListPtr sl = SLCreate(&compareInts);

  int* n1 = malloc(sizeof(int*));
  int* n2 = malloc(sizeof(int*));
  int* n3 = malloc(sizeof(int*));
  int* n4 = malloc(sizeof(int*));
  int* n5 = malloc(sizeof(int*));

  *n1 = 5;
  *n2 = 10;
  *n3 = 3;
  *n4 = 8;
  *n5 = 11;


  printf("Test Case 1: Adding\n");

  SLInsert(sl, n1);
  SLInsert(sl, n2);
  SLInsert(sl, n3);
  SLInsert(sl, n4);

  SortedListIteratorPtr sp = SLCreateIterator(sl);
  
  int* foo;
  do{
    foo = SLNextItem(sp);
    if (foo == NULL) {
      break;
    }
    printf("%d\n", *foo);
  } while (foo != NULL);

  printf("Test Case 2: Removing \n");

  SortedListIteratorPtr sz = SLCreateIterator(sl);

  SLRemove(sl, n4);
  
  do{
    foo = SLNextItem(sz);
    if (foo == NULL) {
      break;
    }
    printf("%d\n", *foo);
  } while (foo != NULL);

  printf("Test Case 3: Removing/Adding in Middle\n");
  SortedListPtr t3 = SLCreate(&compareInts);

  SLInsert(t3, n1);
  SLInsert(t3, n2);
  SLInsert(t3, n3);
  SLInsert(t3, n4);

  SortedListIteratorPtr p3 = SLCreateIterator(t3);

  foo = SLNextItem(p3);
  printf("%d\n", *foo);
  printf("remove: 8, then continue iterating \n");
  SLRemove(t3, n4);
  printf("add 11, then continue iterating \n");
  SLInsert(t3, n5);
  do{
    foo = SLNextItem(p3);
    if (foo == NULL) {
      break;
    }
    printf("%d\n", *foo);
  } while (foo != NULL);
  printf("Iterate whole list from start \n");
  SortedListIteratorPtr p3a = SLCreateIterator(t3);
  do{
    foo = SLNextItem(p3a);
    if (foo == NULL) {
      break;
    }
    printf("%d\n", *foo);
  } while (foo != NULL);

  printf("Test Case 4: Removing and Iterating Empty List\n");
  SortedListPtr t4 = SLCreate(&compareInts);
  SLRemove(t4, n1);
  SortedListIteratorPtr p4 = SLCreateIterator(t4);
  do{
    foo = SLNextItem(p4);
    if (foo == NULL) {
      break;
    }
    printf("%d\n", *foo);
  } while (foo != NULL);
  

  printf("Test Case 5: Strings\n");
  char* c1 = malloc(sizeof(char) * 5);
  char* c2 = malloc(sizeof(char) * 5);
  char* c3 = malloc(sizeof(char) * 5);
  strcpy(c1, "hey\0");
  strcpy(c2, "yo\0");
  strcpy(c3, "kk\0");

  printf("%s\n", c1);
  SortedListPtr t5 = SLCreate(&compareStrings);
  SLInsert(t5, c1);
  SortedListIteratorPtr p5 = SLCreateIterator(t5);
  char *resp = SLNextItem(p5);
  printf("%s\n", resp);


  free(n1);
  free(n2);
  free(n3);
  free(n4);
  free(n5);
  SLDestroyIterator(p4);
  SLDestroyIterator(p3);
  SLDestroyIterator(p3a);
  SLDestroyIterator(sz);
  SLDestroyIterator(sp);
  SLDestroy(sl);
  SLDestroy(t3);
  SLDestroy(t4);
}
Esempio n. 21
0
int main()
{
	Employee *a=(Employee*)malloc(sizeof(Employee));
	a->name="Albert";
	a->salary=48000;

	Employee *b=(Employee*)malloc(sizeof(Employee));
	b->name="Bob";
	b->salary=47000;
	
	Employee *c=(Employee*)malloc(sizeof(Employee));
	c->name="Carter";
	c->salary=46000;
	
	Employee *d=(Employee*)malloc(sizeof(Employee));
	d->name="Dudley";
	d->salary=45000;

	//////////////////////// INITIALISING THE SORTED LIST ///////////////////////////
	SortedListPtr ptr=SLCreate(&compareEmployees, &destroyEmployee);
	printf("Creating SortedList...\n");
	if(SLInsert(ptr, (void *)b))
		printf("Inserted employee with name %s and salary %d \n",b->name,b->salary);
	if(SLInsert(ptr, (void *)a))
		printf("Inserted employee with name %s and salary %d \n",a->name,a->salary);
	if(SLInsert(ptr, (void *)c))
		printf("Inserted employee with name %s and salary %d \n",c->name,c->salary);
	if(SLInsert(ptr, (void *)d))
		printf("Inserted employee with name %s and salary %d \n",d->name,d->salary);
	printf("Finished inserting.\n\n");

	Employee* firstEmp=(Employee*)(ptr->head->data);
  	printf("%s is the first employee in the sorted list. \n\n",firstEmp->name);
  	
  	////////////////////// CREATING ITERATORS //////////////////////////////////////
  	printf("Creating iterator 1 and 2\n");
	SortedListIteratorPtr walker = SLCreateIterator(ptr);
	SortedListIteratorPtr walker2 = SLCreateIterator(ptr);


	printf("Testing SLGetItem for Iterator 1: %s \n", ((Employee*)(SLGetItem(walker)))->name);

	//the walker1 will traverse through the list to the last element
	while(walker->current->next!=NULL){
		SLNextItem(walker);	
		printf("Testing Iterator 1 NextItem: %s \n\n", ((Employee *)(SLGetItem(walker)))->name);
	}

	///////////////// OPERATIONS ON SORTED LISTS //////////////////////////
	printf("Attempting to remove Bob from the list.\n");
	if(SLRemove(ptr, (void *)b))
		printf("Element removed successfully.\n");
	
	//trying to remove from list when iterator points to it
	printf("Attempting to remove Dudley from the SortedList (iterator 1 points to it).\n");
	SLRemove(ptr, (void *)d);
	
  	
  	//destroyed the list but an iterator still points to one of the elements.
  	printf("Attempting to destroy the list. (Note that iterators 1 and 2 are still active.\n\n");
  	SLDestroy(ptr);
  	// testing iterators
  	printf("Iterator 1 is pointing to: %s \n", ((Employee *)(SLGetItem(walker)))->name);
	printf("Iterator 2 is pointing to: %s\n",((Employee *)(SLGetItem(walker2)))->name );
	printf("CHecking next element for each iterator\n");
	if(SLNextItem(walker)==NULL)
		printf("Iterator 1 reaches null\n");
	if(SLNextItem(walker2)==NULL)
		printf("Iterator 2 reaches null\n");
	
	SLDestroyIterator(walker);
	SLDestroyIterator(walker2);

  	return 0;
}
Esempio n. 22
0
int main(int argc, char *argv[]){
	int z = argc;
	if(z==1 || z==0 || z>2){
		printf("too few or many args");
			}
	char *qw = argv[1];					/*argv will pick the option*/
	
	if(strcmp(qw,"1")==0){						/*option 1 is int test*/
	int a = 5;
	int b = 10;
	int c = 7;
	int d = 12;
	int e = 2;
	int f = 9;
	int g = 9;
	int h = 23;
	int i = 50;
	CompareFuncT com = &compareInt;
	DestructFuncT des = &Destroy;
	SortedListPtr s1 = SLCreate(com,des);
	SLInsert(s1,(void*)&a);
	SLInsert(s1,(void*)&b);
	SLInsert(s1,(void*)&c);
	SLInsert(s1,(void*)&d);
	SLInsert(s1,(void*)&e);
	SLInsert(s1,(void*)&f);
	SLInsert(s1,(void*)&g);
	SLInsert(s1,(void*)&h);
	SLInsert(s1,(void*)&i);
	SLRemove(s1,(void*)&e);
	SLRemove(s1,(void*)&d);
	SLRemove(s1,(void*)&h);
	
	while(s1->head!=NULL){
		printf("%d\n",*(int*)s1->head->data);
		s1->head=s1->head->next;
			}
		}

	if(strcmp(qw,"2")==0){						/*option 2 is float test*/
		float ab = 5.21;
		float bc = 10.4;
		float cd = 7.2;
		float de = 12.6;
		float ef = 2.8;
	
	CompareFuncT com = &compareFloat;
	DestructFuncT des = &Destroy;
	SortedListPtr s2 = SLCreate(com,des);
	SLInsert(s2,(void*)&ab);
	SLInsert(s2,(void*)&bc);
	SLInsert(s2,(void*)&cd);
	SLInsert(s2,(void*)&de);
	SLInsert(s2,(void*)&ef);
	SLRemove(s2,(void*)&de);
	SLRemove(s2,(void*)&bc);
	
	while(s2->head!=NULL){
		printf("%.4f\n",*(float*)s2->head->data);
		s2->head=s2->head->next;
			}
		}
	
	

	if(strcmp(qw,"3")==0){						/*option 2 is float test*/
	char *ab = "hello";
	char *bc = "good";
	char *cd = "car";
	char *de = "bus";
	char *ef = "ocean";
	
	CompareFuncT com = &compareString;
	DestructFuncT des = &Destroy;
	SortedListPtr s1 = SLCreate(com,des);
	SLInsert(s1,(void*)ab);
	SLInsert(s1,(void*)bc);
	SLInsert(s1,(void*)cd);
	SLInsert(s1,(void*)de);
	SLInsert(s1,(void*)ef);
	SLRemove(s1,(void*)de);
	SLRemove(s1,(void*)bc);
	
	while(s1->head!=NULL){
		printf("%s\n",(char*)s1->head->data);
		s1->head=s1->head->next;
			}
		}


	if(strcmp(qw,"4")==0){						/*option 2 is float test*/
	char a = 'a';
	char b = 'b';
	char c = 'i';
	char d = 'h';
	char e = 'e';
	
	CompareFuncT com = &compareString;
	DestructFuncT des = &Destroy;
	SortedListPtr s1 = SLCreate(com,des);
	SLInsert(s1,(void*)&a);
	SLInsert(s1,(void*)&b);
	SLInsert(s1,(void*)&c);
	SLInsert(s1,(void*)&d);
	SLInsert(s1,(void*)&e);
	SLRemove(s1,(void*)&d);
	SLRemove(s1,(void*)&b);
	
	while(s1->head!=NULL){
		printf("%c\n",*(char*)s1->head->data);
		s1->head=s1->head->next;
			}
		}
	
	return 0;
		}
Esempio n. 23
0
void * myMalloc(unsigned int size, char * fn, int ln) {
	void 			*ret_ptr;	//Return pointer
	
	memEntry 		*ptr;
	memEntry 		*after;
	
	static memEntry 	*head = 0;	//points to front of memEntry list
	static memEntry 	*tail = 0;	//points to back of memEntry list
    
	ptr = head;
	while(ptr != 0)
	{
		if(ptr->isFree == 0 || (ptr->size < size)) {	//This block is not free or is too small.
			ptr = ptr->next;
		} else if(ptr->size < (size + sizeof(memEntry))) {	//This block is not big enough to cut up.
			ptr->isFree = 0;
			ret_ptr = (char *)ptr + sizeof(memEntry);
			// Adding this block to the list of blocks.
			SLInsert(sl, ret_ptr);
			printf(KGRN "Alloc\'d block 0x%x\n" KNRM, ret_ptr);
			return ret_ptr;
		} else { // Creating the split-up block to come after our newly allocated block.
			after = (memEntry *)((char *)ptr + sizeof(memEntry) + size); //offset from where ptr was; accounts for size of a mementry and the size of the block
			after->prev = ptr;
			after->next = ptr->next;
			if(ptr->next != 0){
				ptr->next->prev = after;
			}
			ptr->next = after;
			after->size = ptr->size - sizeof(memEntry) - size;
			after->isFree = 1;
			ptr->size = size;
			ptr->isFree = 0;
			if (ptr == tail) {
				tail = after;
			}
			ret_ptr = (char *)ptr + sizeof(memEntry);
			// Adding this block to the list of blocks.
			SLInsert(sl, ret_ptr);
			printf(KGRN "Alloc\'d block 0x%x\n" KNRM, ret_ptr);
			return ret_ptr;
		}
	}
	ptr = (memEntry *)sbrk(size + sizeof(memEntry)); //Extending the heap by (size + sizeof(memEntry) bytes if there isn't enough space in any free blocks
	if(ptr == (void *)-1) {
		printf(KRED "Error: Malloc failed in file %s at line %d\n" KNRM, fn, ln);
		return 0;
	} else if(tail == 0) { // tail is null, adds first one
		ptr->prev = 0;
		ptr->next = 0;
		ptr->size = size;
		ptr->isFree = 0;
		head = ptr;
		tail = ptr;
		ret_ptr = (char *)ptr + sizeof(memEntry);
		sl = SLCreate(ptrcmp);
		// Adding this block to the list of blocks.
		SLInsert(sl, ret_ptr);
		printf(KGRN "Alloc\'d block 0x%x\n" KNRM, ret_ptr);
		return ret_ptr;
	} else	{ // otherwise add to existing list
		ptr->prev = tail;
		ptr->next = tail->next;
		ptr->size = size;
		ptr->isFree = 0;
		tail->next = ptr;
		tail = ptr;
		ret_ptr = (char *)ptr + sizeof(memEntry);
		// Adding this block to the list of blocks.
		SLInsert(sl, ret_ptr);
		printf(KGRN "Alloc\'d block 0x%x\n" KNRM, ret_ptr);
		return ret_ptr;
	}
	printf(KRED "Error: Malloc failed in file %s at line %d\n" KNRM, fn, ln);
	return 0;
}
Esempio n. 24
0
void FA(Cache modify, size_t addMe){
	int index2;
	modify->memory_access++;
	long long boff=extract(modify->HMblock,0, addMe);
	long long tag1=extract(modify->HMtag,modify->HMblock, addMe);
	for (int j=0;j<modify->numofSet; j++){
		if(modify->blocks[j][0].valid==1 && modify->blocks[j][0].tag==tag1){
			/*is it the same tag? Hit, update LRU, return*/
			if(modify->LRU!=NULL){
				SLInsert(modify->LRU, j);
				modify->hits++;
				return;
			}
			else{
				/*do nothing to fifo*/
				modify->hits++;
				return;
			}
		}
		if(modify->blocks[j][0].valid==0){
			if(modify->nextLevel!=NULL){
				if(strcmp(modify->nextLevel->type, "direct")==0){
					direct(modify->nextLevel, addMe);
				}	
					if((strlen(modify->nextLevel->type)>=7)&&(strncmp(modify->nextLevel->type,"assoc:", 5)==0)){
					//	printf("I came here");
						SA(modify->nextLevel, addMe, modify->nextLevel->assoc);
					}
					if((strlen(modify->nextLevel->type)==5)&& (strcmp(modify->nextLevel->type,"assoc")==0)){
						FA(modify->nextLevel, addMe);
					}
			}
		
			modify->cold_misses++;
			modify->total_misses++;
			/*updates the queue or DLL*/
			if(modify->LRU!=NULL){
				SLInsert(modify->LRU, j);
			}
			else{
				enqueue(modify->FIFO,j);
			}
			//printf("%d", j);
			modify->blocks[j][0].tag=tag1;
			modify->blocks[j][0].offSet=boff;
			modify->blocks[j][0].valid=1;
		//	printf("\nj is at %d\n", j);
			return;
		}

		if(modify->blocks[j][0].valid==1 &&modify->blocks[j][0].tag!=tag1
			&& j==(modify->numofSet-1)){
				if(modify->nextLevel!=NULL){
				if(strcmp(modify->nextLevel->type, "direct")==0){
					direct(modify->nextLevel, addMe);
				}	
				if((strlen(modify->nextLevel->type)>=7)&&(strncmp(modify->nextLevel->type,"assoc:", 5)==0)){
					//	printf("I came here");
						SA(modify->nextLevel, addMe, modify->nextLevel->assoc);
					}
				if((strlen(modify->nextLevel->type)==5)&& (strcmp(modify->nextLevel->type,"assoc")==0)){
						FA(modify->nextLevel, addMe);
					}
			}
		//		printf("sadI came here %d\n", j);
				/*it's full. Call LRU*/
				modify->total_misses++;
				if(modify->LRU!=NULL){
					index2=getLRU(modify->LRU);}
				else{
					index2=dequeue(modify->FIFO);
				}
			//	printf("\n num: %d\n", index2);
				modify->blocks[index2][0].tag=tag1;
				modify->blocks[index2][0].offSet=boff;
				if(modify->LRU!=NULL){
					SLInsert(modify->LRU, index2);
				}
				else{
					enqueue(modify->FIFO,index2);
				}
				return;
		}
	}
}
Esempio n. 25
0
int main(int argc, char** argv){

printf("Sample test cases, for more test cases look at testcode.txt and at testplan.txt for its expected behavior\n\n");
printf("********************************************* TEST CASE 1 ***********************************************\n\n");

SortedListPtr sl1 = SLCreate(compareInts, NULL);
SLDestroy(sl1);
printf("\n");

printf("********************************************* TEST CASE 6 ***********************************************\n\n");

const char * stringArray[] = {"Zoid", "Brackets", "Apple"};
void * printer;

SortedListPtr sl2 = SLCreate(compareStrings, destroyBasicTypeNoAlloc);

int i;
for(i=0; i<(sizeof(stringArray)/sizeof(stringArray[0])); i++){
	if(SLInsert(sl2, (void *)stringArray[i])==0)
		printf("There was an error but the list was still created anyway\n");
}

SortedListIteratorPtr iter2 = SLCreateIterator(sl2);

printf("List: ");
while((printer=SLNextItem(iter2)) != NULL)
	printf("%s ", (char *)printer);

SLInsert(sl2, "  zoom");
printf("%s ", (char *)SLNextItem(iter2));
printf("\n\n");

SLDestroy(sl2);
SLDestroyIterator(iter2);

printf("********************************************* TEST CASE 8 ***********************************************\n\n");

const char * stringArr[] = {"zoom", "wii", "Soccer", "Zoid", "Brackets", " zoom"};
void * print;
void * print2;

SortedListPtr sl = SLCreate(compareStrings, destroyBasicTypeNoAlloc);

int p;
for(p=0; p<(sizeof(stringArr)/sizeof(stringArr[0])); p++){
	if(SLInsert(sl, (void *)stringArr[p])==0)
		printf("There was an error but the list was still created anyway\n");
}

SortedListIteratorPtr iterator = SLCreateIterator(sl);
SortedListIteratorPtr iterator2 = SLCreateIterator(sl);			

printf("iterator 1: ");
print = SLNextItem(iterator);
printf("%s \n", (char *)iterator->currentNode->data);
		
printf("iterator 2: ");
print2 = SLNextItem(iterator2);
print2 = SLNextItem(iterator2);
printf("%s \n", (char *)iterator2->currentNode->data);	
		

SLRemove(sl, iterator->currentNode->data);
SLRemove(sl, iterator2->currentNode->data);

printf("%s \n", (char *)SLNextItem(iterator));
printf("%s \n", (char *)SLNextItem(iterator2));	

SLDestroyIterator(iterator);
SLDestroy(sl);

return 0;
}
Esempio n. 26
0
int main(int argc, char*argv[])
{
    int choice = atoi(argv[1]);

    
    

    
    printf("Choice: %d\n", choice);
    
    if(choice == 1){
        //1.  Normal SLInserts (@ beginning, middle, end of list)
        //a. integers
        SortedListPtr s = SLCreate(compareInts,destroyBasicTypeAlloc);
        int iarr[6] = {7,5,155,42,-1,6};
        if(populate_list(s,INT,sizeof(iarr)/sizeof(int),iarr,NULL,NULL,NULL) == 0){
            failure();
            return 1;
        }
        SortedListIteratorPtr iter = SLCreateIterator(s);
        iterprint_all(s,iter,INT); //prints 155 42 7 6 5 -1
        
        
    }else if(choice == 2){
        //b. doubles
        SortedListPtr s = SLCreate(compareDoubles,destroyBasicTypeAlloc);
        
        double darr[6] = {7.43,5.55,155.26,42.1,-1.5,6.7};
        if(populate_list(s,DOUBLE,sizeof(darr)/sizeof(double),NULL,darr,NULL,NULL) == 0){
            failure();
            return 1;
        }

        
        SortedListIteratorPtr iter = SLCreateIterator(s);
        iterprint_all(s,iter,DOUBLE); //prints 155.26 42.1 7.43 6.7 5.55 -1.5
        
        
    }else if(choice == 3){
        //c. strings
        SortedListPtr s = SLCreate(compareStrings,destroyBasicTypeAlloc);
        
        char *carr[6] = {"cat","dog","catamaran","apple","cormorant","zebra"};
        if(populate_list(s,STRING,6,0,0,carr,NULL) == 0){
            failure();
            return 1;
        }

        SortedListIteratorPtr iter = SLCreateIterator(s);
        iterprint_all(s,iter,STRING); //prints apple cat catamaran cormorant dog zebra
				      // should print zebra dog cormorant catamaran cat apple
        
        
        
    }else if(choice == 4){
        
        //d. structs
        SortedListPtr s = SLCreate(compareTestStructs,destroyBasicTypeAlloc);
        
        TestStruct strtarr[6];
        strtarr[0].field = 7;
        strtarr[1].field = 5;
        strtarr[2].field = 155;
        strtarr[3].field = 42;
        strtarr[4].field = -1;
        strtarr[5].field = 6;
        
        if(populate_list(s,STRUCT,6,0,0,0,strtarr) == 0){
            failure();
            return 1;
        }
        
        SortedListIteratorPtr iter = SLCreateIterator(s);
        iterprint_all(s,iter,STRUCT); //prints 155 42 7 6 5 -1
    
    }else if(choice == 5){
        //SLRemove nonexistent element
        SortedListPtr s = SLCreate(compareInts,destroyBasicTypeAlloc);
        int iarr[6] = {7,5,155,42,-1,6};
        populate_list(s,INT,sizeof(iarr)/sizeof(int),iarr,0,0,NULL);

        int toremove = 54;
        if (SLRemove(s,&toremove) != 0) {
            failure();
        }else{
            success();
        }
    }else if(choice == 6){
        //SLRemove existing element (no duplicates; didn't handle them anyway)
        SortedListPtr s = SLCreate(compareInts,destroyBasicTypeAlloc);
        int iarr[6] = {7,5,155,42,-1,6};
        populate_list(s,INT,sizeof(iarr)/sizeof(int),iarr,0,0,NULL);


        int toremove = 5;
        
        if (SLRemove(s,&toremove) != 0) {
            SortedListIteratorPtr iter = SLCreateIterator(s);
            iterprint_all_int(s,iter); //prints 155 42 7 6 -1
        }else{
            failure();
        }
        
    }else if(choice == 7){
        //Iterate on empty list
        //Should not fail
        SortedListPtr s = SLCreate(compareInts,destroyBasicTypeAlloc);
        SortedListIteratorPtr iter = SLCreateIterator(s);
        iterprint_all_int(s,iter);
    }else if (choice == 8){
        //SLInsert for item beyond iterator
        SortedListPtr s = SLCreate(compareInts,destroyBasicTypeAlloc);
        int iarr[6] = {7,5,155,42,-1,6};
        populate_list(s,INT,sizeof(iarr)/sizeof(int),iarr,0,0,NULL);
        
        SortedListIteratorPtr iter = SLCreateIterator(s);
        void *item = SLNextItem(iter);
        item = SLNextItem(iter);
        
        int *toins = malloc(sizeof(int));
        *toins = 4;
        SLInsert(s,toins);
        iterprint_all_int(s,iter); //prints 7 6 5 4 -1
        
    }else if(choice == 9){
        //Create multiple iterators on same list, interleave iterations.
        //Delete item between iterators.
        
        SortedListPtr s = SLCreate(compareInts,destroyBasicTypeAlloc);
        int iarr[6] = {7,5,155,42,-1,6};
        populate_list(s,INT,sizeof(iarr)/sizeof(int),iarr,0,0,NULL);
        
        SortedListIteratorPtr olditer = SLCreateIterator(s);
        
        SortedListIteratorPtr iter = SLCreateIterator(s);

        
        void *item;
        
        int i;
        for(i = 0; i < 2; i++){
            item = SLGetItem(olditer);//modify by lezi
            printf("%d ", *((int*)item));
	    item = SLNextItem(olditer);//modify by lezi
        } //prints 155 42
        printf("\n");

        for(i = 0; i < 4; i++){
            item = SLGetItem(iter); //modify by lezi
            printf("%d ", *((int*)item));
            item = SLNextItem(iter);//modify by lezi
        } //prints 155 42 7 6
        printf("\n");  
               
        int itoremove = 6;
        if (SLRemove(s,&itoremove) == 0) {
            failure();
            return 1;
        }
        
        item = SLGetItem(iter);  //prints 5  //modufy by lezi
        printf("%d\n", *((int*)item));
        item = SLGetItem(olditer);
        printf("%d\n", *((int*)item)); //prints 7  //modify by lezi
         
        
        iterprint_all_int(s,iter); //prints 5 -1
        
        iterprint_all_int(s,olditer); //prints 7 5 -1
        
    }else if(choice == 10){
        //SLRemove end element, iterator positioned on it
        
        SortedListPtr s = SLCreate(compareInts,destroyBasicTypeAlloc);
        int iarr[3] = {7,5,3};
        populate_list(s,INT,sizeof(iarr)/sizeof(int),iarr,0,0,NULL);

        
        SortedListIteratorPtr iter = SLCreateIterator(s);

        int x3 = 3;
        void *item = SLNextItem(iter);
        item = SLNextItem(iter);//iterator points to 3
        if(SLRemove(s,&x3) && SLNextItem(iter) == NULL){
            success();
        }else{
            failure();
        }
        
    }else if(choice == 11){ //TODO
        //SLRemove element in middle, iterator positioned on it
        SortedListPtr s = SLCreate(compareInts,destroyBasicTypeAlloc);
        int iarr[3] = {7,5,3};
        populate_list(s,INT,sizeof(iarr)/sizeof(int),iarr,0,0,NULL);
        
        SortedListIteratorPtr iter = SLCreateIterator(s);
        void *item = SLNextItem(iter);
        
        int x1 = 5;
        if(SLRemove(s,&x1) && *((int*)SLNextItem(iter)) == 3 &&
           ((int*)SLNextItem(iter)) == NULL){
            success();
        }else{
            failure();
        }
        
        
        
        
    }else if(choice == 12){
        //SLRemove element positioned immediately after element iterator is pointing to
        SortedListPtr s = SLCreate(compareInts,destroyBasicTypeAlloc);
        int iarr[6] = {7,5,155,42,-1,6};
        populate_list(s,INT,sizeof(iarr)/sizeof(int),iarr,0,0,NULL);
        

        SortedListIteratorPtr iter = SLCreateIterator(s);
        void *item = SLNextItem(iter);
        item = SLNextItem(iter);
        int x1 = 6;
        if(SLRemove(s,&x1) && *((int*)SLGetItem(iter)) == 7 //modify by lezi
           && *((int*)SLNextItem(iter)) == 5
           && *((int*)SLNextItem(iter)) == -1
           && ((int*)SLNextItem(iter)) == NULL){
            success();
        }else{
            failure();
        }
        
    }else if(choice == 13){
        //Add item between recently returned element and element about to be returned.
        SortedListPtr s = SLCreate(compareInts,destroyBasicTypeAlloc);
        int iarr[3] = {7,5,3};
        populate_list(s,INT,sizeof(iarr)/sizeof(int),iarr,0,0,NULL);
        
        SortedListIteratorPtr iter = SLCreateIterator(s);
        void *item = SLNextItem(iter);
        item = SLNextItem(iter);//point to 3 now
        int *x4 = malloc(sizeof(int));
        *x4 = 4;
        SLInsert(s,x4);
        
        iterprint_all_int(s,iter); //prints 3
        

        
        
    }else if(choice == 14){
        //Add item to head and middle, after iterator has been created //modify by Lezi
        SortedListPtr s = SLCreate(compareInts,destroyBasicTypeAlloc);
        int iarr[3] = {7,5,3};
        populate_list(s,INT,sizeof(iarr)/sizeof(int),iarr,0,0,NULL);
        
        SortedListIteratorPtr iter = SLCreateIterator(s);
        int *toinsert = malloc(sizeof(int));
        *toinsert = 8;
        SLInsert(s,toinsert);
        int *toinsert1 = malloc(sizeof(int));
  	*toinsert1 = 4; // add by lezi
	SLInsert(s,toinsert1);//add by lezi
        
        iterprint_all_int(s,iter); //prints 7 5 4 3 //modify by lezi
    }else if(choice == 15){
        
        //Add item to tail after all items have been returned by iterator.
        SortedListPtr s = SLCreate(compareInts,destroyBasicTypeAlloc);
        int iarr[3] = {7,5,3};
        populate_list(s,INT,sizeof(iarr)/sizeof(int),iarr,0,0,NULL);
        
        SortedListIteratorPtr iter = SLCreateIterator(s);
        void *item;
        while((item = SLNextItem(iter)) != NULL);
        
        
        int *toins = malloc(sizeof(int));
        *toins = -1;
        SLInsert(s,toins);
        
        if(SLGetItem(iter) == NULL){ //modify by lezi
            success();
        }else{
            failure();
        }
    }else{
        printf("Bad input\n");
    }
    
    
    return 0;
    
}
Esempio n. 27
0
int main(void)
{
//TEST CASE 1 WITH CHARACTERS
  SortedListPtr si =SLCreate(compareStrings, destroy);
  
  SLInsert(si, "z");
  SLInsert(si, "a");
  SLInsert(si, "a");
  SLInsert(si, "b");
  SLInsert(si, "x");
  printf("\n=-=-=-=-=-=-=- Testing Characters =-=-=-=-=-=-=-=-=-=-=-=-=-=\n");
  printf("Completed inserting characters into list\n");
// SLRemove(si, "x");
    
  Node *ptr;
  SortedListIteratorPtr it =  SLCreateIterator(si);
  
  //iterator has been created, begin to iterate through the list and print out the values
  //we use the SLGetItem to return the current item 
  ptr =SLGetItem(it);	  
  while(ptr != NULL)
  {
	  printf("\n%s", ptr->data);
	  ptr = SLNextItem(it);  //uses the SLNextItem to move the pointer to the next item to continue iterating
  }
  printf("\nCompleted interating through the list\n");
  
  //The iterator gets destroyed 
  SLDestroyIterator(it); 
  printf("Iterator has been destroyed\n");
  
  //the list has not been affected since the iterator got destroyed
  printf("Destroyed iterator does not affect list by printing out values from list\n");
  printf("First item in the list: %s\n", si->head->data); //prints out the item in the list where head points to
  printf("Second item in the list: %s\n", si->head->next->data); //prints out the item after head
  printf("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n");	
//+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+	


//TEST CASE 2 WITH INTEGERS 
 
 	int arr[]= {2,3,10,8,4,11,21,8,1,7,16};
	 
	int length = sizeof(arr)/sizeof(arr[0]);
	
	int i;
	
	SortedListPtr si2 =SLCreate(compareInts, destroy);
	int *intPtr;
	
	int x = 100;              //
	int *insrt;               //   to insert a number 100
	insrt = &x;              //    after iterated through list
 printf("\n=-=-=-=-=-=-=-=-=-Testing Integers=-=-=-=-=-=-=-=-=-=-=-=\n");
 
  //inserts numbers from arrray into linked list 
	for(i = 0; i < length;i++)
	{
		intPtr = &arr[i];
		SLInsert(si2,intPtr);
	}
  printf("Finished inserting numbers into linked list\n");
  	
  Node* ptr2;
  SortedListIteratorPtr it2 =  SLCreateIterator(si2);
  ptr2 = SLGetItem(it2);
 
  //iterator traverses through the list
  while(ptr2 != NULL)
  {   
      printf("%d\n", (*(int*)(ptr2->data)) );
  	  ptr2 = SLNextItem(it2);
  } 
  printf("Finished traversing through linked list\n");  
  
  SLInsert(si2, insrt);
  printf("Number 100 has been inserted into the list\n");
  
  //destroys iterator
  SLDestroyIterator(it2);
  printf("Iterator has been destroyed\n");
  
  //list has not been affectedby iterator by printing values in list
  printf("First value in list: %d\n",  (*(int*)(si2->head->data))   );
  printf("Second value in list: %d\n",  (*(int*)(si2->head->next->data))   );
  
  
  //remove item from list
 SLRemove(si2, insrt);
 printf("item containing 100 has been deleted from list\n");
 printf("First item after deletion:%d\n",  (*(int*)(si2->head->data)) );  
 printf("Second item after deletion:%d\n",  (*(int*)(si2->head->next->data)) );  
 printf("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n");
 
 //TESTING FLOATS--------------------------
float arrDbl[]= {2.2,3.6,10.9,8.3,4.7,11.3,21.7,8.1,1.8,7.2,16.5};
	 
	int size = sizeof(arrDbl)/sizeof(arrDbl[0]);
	
	int count;
	
	SortedListPtr si3 =SLCreate(compareDoubles, destroy);
	float *dblPtr;
	
	float var = 170.5;              
	float *insert;             
	insert = &var;           
 printf("\n=-=-=-=-=-=-=-=-=-Testing Floats=-=-=-=-=-=-=-=-=-=-=-=\n");
 
  //inserts numbers from arrray into linked list 
	for(count = 0; count < size;count++)
	{
		dblPtr = &arrDbl[count];
		SLInsert(si3,dblPtr);
	}
  printf("Finished inserting numbers into linked list\n");
  	
  Node* ptr3;
  SortedListIteratorPtr it3 =  SLCreateIterator(si3);
  ptr3 = SLGetItem(it3);
 
  //iterator traverses through the list
  while(ptr3 != NULL)
  {   
      printf("%f\n", (*(float*)(ptr3->data)) );
  	  ptr3 = SLNextItem(it3);
  } 
  printf("Finished traversing through linked list\n");  
  
  SLInsert(si3, insert);
  printf("Number 170.5 has been inserted into the list\n");
  
  //destroys iterator
  SLDestroyIterator(it3);
  printf("Iterator has been destroyed\n");
  
  //list has not been affectedby iterator by printing values in list
  printf("First value in list: %f\n",  (*(float*)(si3->head->data))   );
  printf("Second value in list: %f\n",  (*(float*)(si3->head->next->data))   );
  
  
  //remove item from list
 SLRemove(si3, insert);
 printf("item containing 100 has been deleted from list\n");
 printf("First item after deletion:%f\n",  (*(float*)(si3->head->data)) );  
 printf("Second item after deletion:%f\n",  (*(float*)(si3->head->next->data)) );  
 printf("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n");
 
	return 0;
}
Esempio n. 28
0
void addToList(char *fS, SortedList1Ptr SL, char *pathName)
{
			TokenizerT* tokenizer = TKCreate(" ", fS);
			Node1* temp;

			if(tokenizer == NULL) {
				printf("Error: unable to create tokenizer\n");
			}
			char* token = NULL;
			while((token = TKGetNextToken(tokenizer)) != NULL) {
			if(SL==NULL)
			{
				printf("SL CREATED\n");
				SL = SLCreate(token, pathName);
				//printf(SL->root->token);
				temp = SL->root;
			while(temp!=NULL)
			{
				printf("%s->",temp->token);
				temp=temp->next;
			}

			printf("\n");
			}
			else
			{
#ifdef DEBUG
				printf("***************TOKEN ADDED: %s\n", token);
				printf("***************Pathname ADDED: %s\n", pathName);
#endif

				SLInsert(SL, token, pathName);
				if(strcmp(pathName, "") == 0) printf("\n%spathname is blank%s\n",KRED, KNORM);
				else printf("\n%s%s%s\n", KRED, pathName, KNORM);
				printlist(SL);

			//	printf(SL->root->token);
			//	temp = SL->root;
			while(temp!=NULL)
			{
				printf("%s->",temp->token);
				temp=temp->next;
			}

			printf("\n");

			}
			//			free(token); ????????????
			}

	 printf("Main(): Final result, print the ROOT from Vertical SL: %s\n", SL->root->token );
        printf("Main(): Final result, print the ROOT's filename from Vertical SL: %s\n", SL->root->accessToNode2->fileName );
        printf("Main(): Final result, print the ROOT's frequency from Vertical SL: %d\n", SL->root->accessToNode2->frequency);
//      printf("Main(): 2 items in HSL : Final result, print the ROOT's frequency from Vertical SL: %s\n", SLMain->root->accessToNode2->next->fileName);
//      printf("Main(): 2 items in HSL : Final result, print the ROOT's frequency from Vertical SL: %d\n", SLMain->root->accessToNode2->next->frequency);


        printf("Main():22222 Final result, print the ROOT from Vertical SL: %s\n", SL->root->next->token );
        printf("Main():22222 Final result, print the ROOT's filename from Vertical SL: %s\n", SL->root->next->accessToNode2->fileName );
        printf("Main():22222 Final result, print the ROOT's frequency from Vertical SL: %d\n", SL->root->next->accessToNode2->frequency);

        printf("Main():33333 Final result, print the ROOT from Vertical SL: %s\n", SL->root->next->next->token );
        printf("Main():33333 Final result, print the ROOT's filename from Vertical SL: %s\n", SL->root->next->next->accessToNode2->fileName );
        printf("Main():33333 Final result, print the ROOT's frequency from Vertical SL: %d\n", SL->root->next->next->accessToNode2->frequency);

        printf("Main():55555 Final result, print the ROOT from Vertical SL: %s\n", SL->root->next->next->next->token );

	TKDestroy(tokenizer);

}
Esempio n. 29
0
void add_word(char *filename, char *wordToAdd, char *tokenString) {

	FileWithCount file;
	file = (FileWithCount) malloc( sizeof(FileWithCount) );
	file->filename = (char *) malloc( BUFSIZ+1 );
	snprintf(file->filename, BUFSIZ, "%s", filename);
		
	file->count = 1;
	printf("Filename after file %s and should be %s\n",file->filename,filename);

	/*Find if word exists*/
	WordNode wordToFind = (WordNode) malloc(sizeof(WordNode));
	wordToFind->word = (char *) malloc (BUFSIZ+1);
	snprintf(wordToFind->word, BUFSIZ, "%s", wordToAdd);
	
	WordNode isWordThere;
	isWordThere = (WordNode) SLFind(wordList, wordToFind);
	
	
	if (isWordThere != NULL) { 				/*Word already exists*/
		printf("WORD EXISTS:  %s\n", wordToAdd);
		
		SortedListIteratorPtr iter;
		iter = SLCreateIterator(isWordThere->files);
		void *obj = NULL;
		while ((obj = SLNextItem(iter))) {
			FileWithCount objFile;
			objFile = obj;		

			if (compareFilesWithCount(objFile, file) == 0) {
			/*Filename present,
				just increase count and break*/
				objFile->count++;
				break;
			}
		}
		SLDestroyIterator(iter);
		
		if(obj == NULL) {
		/*File not found, insert it into list*/
			printf("Filename before slinsert %s\n",file->filename);
			SLInsert(isWordThere->files, file);
			printf("Inserted file %s into word %s\n",file->filename,isWordThere->word);
			printf("Filename actually %s\n",filename);
			free (wordToFind->word);
			free (wordToFind);
			
		} else {
			fprintf(stderr, "ERROR: Add Word\n");
			free (file->filename);
			free (file);
			free (wordToFind->word);
			free (wordToFind);			
		}

		return;
	} else {						/*Word doesn't exist yet*/

		wordToFind->files = SLCreate(compareFilesWithCount);
		/* printf("The word of the day is %s\n", w->word); */
		
		/*Insert file path into word*/
		SLInsert(wordToFind->files, file);
		/*Insert word into word list*/
		SLInsert(wordList, wordToFind);

		return;
	}
	
}
Esempio n. 30
0
int readFile(struct List *list, const char* filename){

	int fileSize = 0;
	char* str;
	int i = 0;
	char c;
	char* buffer;
	
	int rval;
	rval =access(filename,R_OK);

	if (rval==0){
	//you have read permission

	}
	else if(errno==EACCES){
	printf("you do not have access to %s\n",filename);
	return 0;

	}


	//read in file, put in big string 
	FILE *filePtr = fopen(filename, "r");
	
	if(filePtr == NULL){
		return -1;
	}

	fseek(filePtr, 0, SEEK_END);
	fileSize = ftell(filePtr);
	fseek(filePtr, 0, SEEK_SET);
	str = (char*)malloc(sizeof(char)*fileSize+1);
	
	while((c = fgetc(filePtr)) != EOF){

		str[i] = tolower(c);
		i++;

	}

	str[i] = '\0';
	fclose(filePtr);


	//tokenize string
	TokenizerT *tok;
	tok = TKCreate(str);	


	indexPointer = tok->input;

	while (indexPointer != '\0'){

		buffer = TKGetNextToken(tok);

		if(strlen(buffer) > 0){

			SLInsert(list, buffer, filename);
		}

		free(buffer);

	}
	TKDestroy(tok);
	free(str);
	return 0;

}