Skip to content

Instantly share code, notes, and snippets.

@wheelercj
Last active May 5, 2022 20:10
Show Gist options
  • Save wheelercj/299d03080d69b59547e7678faa7a1009 to your computer and use it in GitHub Desktop.
Save wheelercj/299d03080d69b59547e7678faa7a1009 to your computer and use it in GitHub Desktop.
full example solution for the second set of practice problems in "intro to recursion with C++" here: https://wheelercj.github.io/notes/pages/20220502232349.html
#include <iostream>
using namespace std;
struct Node {
int value = 0;
Node* next = NULL;
Node(int new_value) {
value = new_value;
}
};
void append(int new_value, Node** next_ptr);
void print_list(Node* node_ptr);
int find_sum(Node* node_ptr);
int find_length(Node* node_ptr);
int find_value(int target, Node* node_ptr, int i);
void insert(int new_value, int index, Node** next_ptr);
void delete_list(Node* head);
int main() {
Node* list_head = NULL;
append(11, &list_head);
append(12, &list_head);
append(13, &list_head);
append(14, &list_head);
print_list(list_head);
int sum = find_sum(list_head);
cout << "\nsum = " << sum;
int length = find_length(list_head);
cout << "\nlength = " << length;
int index = find_value(12, list_head, 0);
cout << "\nindex of 12 = " << index;
cout << endl;
insert(8, 3, &list_head);
print_list(list_head);
delete_list(list_head);
cout << endl;
return 0;
}
void append(int new_value, Node** next_ptr) {
if (*next_ptr == NULL)
*next_ptr = new Node(new_value);
else
append(new_value, &(*next_ptr)->next);
}
void print_list(Node* node_ptr) {
if (node_ptr == NULL)
return;
cout << node_ptr->value << " ";
print_list(node_ptr->next);
}
int find_sum(Node* node_ptr) {
if (node_ptr == NULL)
return 0;
return node_ptr->value + find_sum(node_ptr->next);
}
int find_length(Node* node_ptr) {
if (node_ptr == NULL)
return 0;
return 1 + find_length(node_ptr->next);
}
int find_value(int target, Node* node_ptr, int i) {
if (node_ptr == NULL)
return -1;
if (target == node_ptr->value)
return i;
return find_value(target, node_ptr->next, i + 1);
}
void insert(int new_value, int index, Node** next_ptr) {
if (index == 0) {
Node* new_node = new Node(new_value);
new_node->next = *next_ptr;
*next_ptr = new_node;
}
else if (*next_ptr == NULL)
cout << "Error! Invalid index." << endl;
else
insert(new_value, index - 1, &(*next_ptr)->next);
}
void delete_list(Node* head) {
if (head == NULL)
return;
delete_list(head->next);
delete head;
head = NULL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment