{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

25S-Section-Solution

25S-Section-Solution - CS106X Autumn 2010 Handout 25S...

This preview shows pages 1–2. Sign up to view the full content.

CS106X Handout 25S Autumn 2010 October 27 th – 29 th , 2010 Section Solution Solution 1: Removing Duplicates void RemoveDuplicates(node *list) { for (node *cur = list; cur != NULL; cur = cur->next) { if (cur->next != NULL && cur->value == cur->next->value) { // match? node *duplicate = cur->next; // remember cur->next = cur->next->next; // circumvent delete duplicate; // dispose } } } Solution 2: Braided Lists struct node { int value; node *next; }; The recursive approach is easier to code up, but requires more a much more clever algorithm. void Braid(node *list) { Queue<int> numbers; BraidRec(list, numbers); } void BraidRec(node *list, Queue<int>& numbers) { if (list == NULL) return; numbers.enqueue(list->value); BraidRec(list->next, numbers); node *newNode = new node; newNode->value = numbers.dequeue(); newNode->next = list->next; list->next = newNode; } A fully iterative approach is best handled in two passes: void Build(node *list) { node *reverse = NULL; for (node *curr = list; curr != NULL; curr = curr->next) { node *newNode = new node; newNode->value = curr->value; newNode->next = reverse; reverse = newNode; }

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

Page1 / 3

25S-Section-Solution - CS106X Autumn 2010 Handout 25S...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online