void addAtIndex(LinkedList** ll, char* str, int index) { char* string = (char*)malloc(6*sizeof(char*)); strcpy(string, str); LinkedList* nn = (LinkedList*)malloc(1*sizeof(LinkedList)); nn->value = string; nn->next = NULL; LinkedList* p = *ll; if ((index == 0 && p == NULL) || (index == (size(*ll) - 1)) ) { //(index is zero and size is zero) or (index is the last in the array) llAdd(ll, string); } else if (index == 0 && p != NULL) { LinkedList** newLL = ll; *newLL = nn; nn->next = p; } else if ((index < size(*ll)) && (index > 0)) { //index is between 0 and size and size is greater than 0 int i = 0; while(i < (index - 1)) { p = p->next; i++; } LinkedList* tmp = p->next; p->next = nn; nn->next = tmp; } }
int main() { LinkedList* ll = llCreate(); llDisplay(ll); char* s = (char*)malloc(6*sizeof(char)); s[0] = 'h'; s[1] = 'e'; s[2] = 'l'; s[3] = 'l'; s[4] = 'o'; s[5] = '\0'; llAdd(&ll, s); // llAdd(ll, 5); // llAdd(ll, 7); llDisplay(ll); }
int main() { LinkedList* ll = llCreate(); char* str = "hello"; char* str2 = "ping"; char* str3 = "pong"; char* str4 = "pinga"; char* str5 = "da"; char* str6 = "ponga"; char* str7 = "yup"; llAdd(&ll, str); llAdd(&ll, str); llAdd(&ll, str); llAdd(&ll, str4); llAdd(&ll, str); llAdd(&ll, str6); printf("LinkedList after adding a bunch of strings:\n"); llDisplay(ll); printf("Size: %d\n\n", size(ll)); int index = 4; printf("LinkedList after adding '%d' at index %d:\n", str7, index); addAtIndex(&ll, str7, index); llDisplay(ll); printf("Size: %d\n\n", size(ll)); index = 3; printf("LinkedList after removing the word at index %d:\n", index); removeAtIndex(&ll, index); llDisplay(ll); printf("Size: %d\n\n", size(ll)); printf("LinkedList after removing all instances of %d:\n", str); removeString(&ll, str); llDisplay(ll); printf("Size: %d\n\n", size(ll)); llAdd(&ll, str); llAdd(&ll, str); llAdd(&ll, str); llAdd(&ll, str4); llAdd(&ll, str); llAdd(&ll, str6); printf("LinkedList after repopulation:\n"); llDisplay(ll); llDelete(&ll); printf("Size: %d\n", size(ll)); }