// File: stringitem.C // // string operations needed for ListNode and List Classes. #include #include #include #include "stringitem.h" // default constructor // ListItem::ListItem() { str = NULL ; } // alternate constructor // ListItem::ListItem(const ListItem &x) { if (x.str == NULL) { str = NULL ; return ; } str = strdup(x.str) ; if (str == NULL) { fprintf(stderr, "could not duplicate string\n") ; exit(1) ; } } // type converter // ListItem::ListItem(const char *s) { if (s == NULL) { str = NULL ; return ; } str = strdup(s) ; if (str == NULL) { fprintf(stderr, "could not duplicate string\n") ; exit(1) ; } } // destructor // ListItem::~ListItem() { /* Debugging: printf("ListItem Destructor: (%p, %s)\n", item, item) ; */ if (str != NULL) free(str) ; } // make a copy // ListItem *ListItem::copy() const { ListItem *newp ; newp = new ListItem ; if (str == NULL) return newp ; newp->str = strdup(str) ; if (newp->str == NULL) { fprintf(stderr, "could not duplicate string\n") ; exit(1) ; } return newp ; } // Copy contents of host object to x // void ListItem::copyto(ListItem &x) const { if (x.str != NULL) { free(x.str) ; x.str = NULL ; } if (str == NULL) return ; x.str = strdup(str) ; if (x.str == NULL) { fprintf(stderr, "could not duplicate string\n") ; exit(1) ; } return ; } // Compare data in host object with given data. // <0 is smaller, =0 is equal, >0 is bigger // int ListItem::compare(const ListItem& x) const { if (str == NULL && x.str == NULL) return 0 ; if (str == NULL) return -1 ; if (x.str == NULL) return 1 ; return strcmp(str, x.str) ; } // print to stdout // void ListItem::print() const { if (str != NULL) { printf("%s", str) ; } }