#include <iostream>

using std::cout;
using std::cin;

typedef struct LinkedList {
  int value;
  struct LinkedList *next;
} LinkedList;

LinkedList* create_node(int x) {
  // Create space in memory for new node.
  LinkedList* node = new LinkedList();
  // Initialize fields.
  node->value = x;
  node->next = nullptr;
  return node;
}

LinkedList* add_node(LinkedList* head, int x) {
  LinkedList* new_head = create_node(x);
  new_head->next = head;
  return new_head;
}

void print_list(LinkedList* head) {
  cout << "List: ";
  while (head) {
    // Print value at current node and advance to next.
    cout << head->value << ", ";
    head = head->next;
  }
  cout << '\n';
}

void delete_list(LinkedList* head) {
  LinkedList* next;
  while (head) {
    // Save address of next node before deleting this.
    next = head->next;
    delete head;
    // Advance to next node.
    head = next;
  }
}

int main() {
  int n;
  cout << "Type in a size: ";
  cin >> n;

  LinkedList* head = nullptr;
  for (int i=0; i < n; i++) {
    head = add_node(head, i);
  }

  print_list(head);
  delete_list(head);
  print_list(head); // undefined behavior!
  // We deleted our list, so we have an "old" pointer.
  // After deleting something, it's important to reset addresses.
  // So after delete_list, we should have head = nullptr;

  return 0;
}
