/* * linklist.c * * Walter Goodwater * * CSc 300: Copyright Violation Lab */ #include "linklist.h" Nodeptr previous = NULL; Nodeptr current = NULL; Nodeptr temp = NULL; Nodeptr create( char * name, int age, Nodeptr next ) { Nodeptr newNode = (Nodeptr)malloc(sizeof(struct Node)); newNode->name = (char*)malloc( sizeof(strlen(name) + 1) ); strcpy(newNode->name, name); newNode->next = next; newNode->age = age; return newNode; } Nodeptr insert( char* name, int age, Nodeptr header ) { /* Case 1: if node is to be inserted into an empty list */ if( header == NULL ) { header = create( name, age, NULL ); } /* Case 2: if node needs to go before the header */ else if( header->age < age ) { header = create( name, age, header ); } else { previous = header; current = header->next; while( current != NULL && age < current->age ) { previous = current; current = current->next; } /* Case 3: if the node should go at the end of the list */ if( current == NULL ) { previous->next = create( name, age, NULL ); } /* Case 4: if node is in the middle of the list */ else if( age > current->age ) { previous->next = create( name, age, current); } } return header; } Nodeptr delete( char *name, Nodeptr header ) { /* Case 1: if list is empty */ if( header == NULL ) { printf("\nNothing to delete\n"); return header; } /* Case 2: if node to delete is first in list */ else if( strcmp( header->name, name ) == 0 ) { temp = header; header = header->next; return header; } /* Case 3: if node to delete is within middle of list */ else { previous = header; current = header->next; while( current != NULL && strcmp( name, current->name ) != 0 ) { previous = current; current = current->next; } /* Case 4: if word to be deleted is not in list */ if( current == NULL ) { printf("\nName is not in list\n"); return header; } /* Case 5: if word is in the list */ else if( strcmp( name, current->name ) == 0 ) { temp = current; previous->next = current->next; free(current); } } return header; } void print( Nodeptr header ) { current = header; if( current == NULL ) { printf("\nYour linked list is currently empty -- nothing to print\n"); exit(-1); } while( current != NULL ) { printf("Name: %s", current->name ); printf("Age: %i", current->age ); current = current->next; } }