#include<stdlib.h>
#include<stdio.h>
#include<string.h>
typedef struct linked_list_elem {
char *val;
struct linked_list_elem* next;
} t_linked_list_elem;
t_linked_list_elem* head = NULL;
t_linked_list_elem* tail = NULL;
// Finds given string in given linked list.
// returns: the t_linked_list_elem matching the string if found,
// NULL otherwise.
t_linked_list_elem* findItem (const char* string);
// If string already existed in the list, returns the existing item.
// Else adds given string at the end of list and returns the added item.
t_linked_list_elem* addItem (const char* string);
void printList ();
int main() {
FILE* tFile;
tFile = fopen ("D:\\Temp\\myFile.txt", "r"); // assume the file exists and has data
char buf[35];
//curr= head;
while (!feof (tFile)) {
fscanf (tFile, "%s", buf);
//printf ("BEFORE ADDING: %s", buf);
//printList ();
addItem (buf);
//printf ("AFTER ADDING: %s", buf);
//printList ();
}
printf ("\n\nFinal List\n");
printList ();
return 0;
}
t_linked_list_elem* findItem (const char* string) {
if (head != NULL) {
t_linked_list_elem* curr = head;
do {
if (0 == strcmp (string, curr->val))
return curr;
else
curr = curr->next;
} while (curr != NULL);
}
return NULL;
}
t_linked_list_elem* addItem (const char* string) {
t_linked_list_elem* existing = findItem (string);
if (existing != NULL) {
printf("Trying to add an item (%s) that already existed. Would be ignored.\n", string);
return existing;
}
t_linked_list_elem* newItem = (t_linked_list_elem*) malloc (sizeof (t_linked_list_elem));
newItem->val = (char*) malloc (strlen (string) * sizeof (char) + 1);
strcpy (newItem->val, string);
newItem->next = NULL;
if (NULL == head) {
head = newItem;
tail = head;
} else {
tail->next = newItem;
tail = newItem;
}
return tail;
}
void printList () {
printf ("\nList -- ");
if (head != NULL) {
t_linked_list_elem* curr = head;
do {
printf ("[%s] ", curr->val);
curr = curr->next;
} while (curr != NULL);
}
printf (" --\n");
} --edit--
This is what hte output looks like: Trying to add an item (hippo) that already existed. Would be ignored.
Trying to add an item (cat) that already existed. Would be ignored.
Final List
List -- [hippo] [cat] [dog] [giraffe] [kitty] [rhino] --
thekashyap
Practically a Posting Shark
811 posts since Feb 2007
Reputation Points: 254
Solved Threads: 75