/* task9_4.cpp */
#include <iostream>
#include <cassert>
#include <iomanip>

using namespace std;

struct T {
  int i;
  T *next;

  void createLinkedList(int size);
  void printLinkedList();
  void cleanupLinkedList();
};



void T::createLinkedList(int size) {
  assert(size > 0);
  T *source = this;
  this->i = 0;
  T *next = this;
  for (int i = 0; i < size - 1; ++i) {
    next = new T;
    next->i = i + 1;
    source->next = next;
    source = next;
  }
  next->next = 0;
}


void T::printLinkedList() {
  T *current = this;
  while (current->next) {
    cout << dec << "#" << setw(2) << current->i << ":  addr: "
         << hex << (long)current->next << endl;
    current = current->next;
  }
  cout << dec << "#" << setw(2) << current->i << ":  addr: "
       << (current->next == 0 ? "0" : "???") << endl;
}


void T::cleanupLinkedList() {
  T *current = this;
  T *next = this;
  while ((next = current->next) != 0) {
    delete current;
    current = next;
  }
  delete current;
}


int main(int argc, char* argv[]) {
  T *head = new T;
  head->createLinkedList(12);
  head->printLinkedList();
  head->cleanupLinkedList();
  head = 0;

  head = new T;
  head->createLinkedList(1);
  head->printLinkedList();
  head->cleanupLinkedList();
  head = 0;
}
