/***********************************************************************/ /* String List Utilities */ /* Solutions */ /* */ /* Author: Mark A. Sheldon, Tufts University, Fall 2012 */ /***********************************************************************/ #include using std::cout; #include "StringList.h" #include "StringListUtils.h" /* * Can use a while or for loop. */ void print(StringListNode *list) { cout << "["; while (!isEmpty(list)) { cout << first(list); if (!isEmpty(rest(list))) cout << ", "; list = rest(list); } cout << "]"; } // 4 ~> 3 ~> () void printArtistically(StringListNode *list) { if (isEmpty(list)) cout << "()"; else { cout << first(list) << " ~> "; printArtistically(rest(list)); } } // Return the length (number of non-empty nodes in) list. int length(StringListNode *list) { return isEmpty(list) ? 0 : 1 + length(rest(list)); } string concat_all(StringListNode *list) { if (isEmpty(list)) return ""; else return first(list) + concat_all(rest(list)); } StringListNode *copy(StringListNode *list) { if (isEmpty(list)) return empty(); else return prepend(first(list), copy(rest(list))); } StringListNode *mapPluralize(StringListNode *words) { if (isEmpty(words)) return empty(); else return prepend(first(words) + "s", mapPluralize(rest(words))); } StringListNode *pairwiseConcat(StringListNode *a, StringListNode *b) { if (isEmpty(a) and isEmpty(b)) return empty(); else if (isEmpty(a) and not isEmpty(b)) return prepend(first(b), pairwiseConcat(a, rest(b))); else if (not isEmpty(a) and isEmpty(b)) return prepend(first(a), pairwiseConcat(rest(a), b)); else // both a and b are non-empty return prepend(first(a) + first(b), pairwiseConcat(rest(a), rest(b))); } void deleteList(StringListNode **p_list) { while (not isEmpty(*p_list)) *p_list = deleteFirst(*p_list); // *p_list now contains the empty list. }