Skip to content

Instantly share code, notes, and snippets.

@lazanet
Last active September 14, 2017 23:29
Show Gist options
  • Save lazanet/93904ec93c125cb0d07f524b994d9b4b to your computer and use it in GitHub Desktop.
Save lazanet/93904ec93c125cb0d07f524b994d9b4b to your computer and use it in GitHub Desktop.
bcc3.1 list "template"
#ifndef __LIST_H__
#define __LIST_H__
#include <iostream.h>
#define makeNormalList(type) makeList(List_##type, type)
#define makePointerList(t) makeList(List_pointer##t, t *)
#define makeList(name, type)\
class name {\
public: \
type data;\
name * next;\
name * last();\
name (type d):data(d), next(NULL){}\
name (type d, name * n):data(d),next(n){}\
static void insert_front(name ** l, type data);\
static void insert_back(name ** l, type data);\
static name * removeItem(name ** l, name * before, name * elem);\
void printList();\
};\
name * name :: last()\
{\
name * l = this;\
while (l && l->next)\
l=l->next;\
return l;\
}\
void name :: insert_front(name** l, type data)\
{\
name * t = new name (data);\
t->next = *l;\
*l = t;\
}\
void name :: insert_back(name** l, type data)\
{\
name * t = new name (data);\
name * last = (*l)->last();\
if (!last)\
*l = t;\
else\
last->next = t;\
}\
name * name :: removeItem(name ** l, name * before, name * elem)\
{\
if (!elem) return NULL;\
name * sled = elem -> next;\
if (!before)\
*l = sled, delete elem;\
else \
before -> next = sled, delete elem;\
return sled;\
}\
void name :: printList()\
{\
name * l = this;\
while (l)\
cout<<l->data<<endl, l = l->next;\
}
#endif
@lazanet
Copy link
Author

lazanet commented Sep 14, 2017

Usage:

#include <iostream.h>
#include "LIST.H"

makeList(List_int, int) // same as makeNormalList(int)
makeList(List_pointerint, int *) // first parameter is suffix name for class, second is data type stored in it

List_pointerint * l1;
List_int * list;

int main(int argc, char * argv[])
{
  List_int::insert_front(&list,0);
  List_int::insert_back(&list,1);
  List_int::insert_back(&list,2);
  List_int::insert_back(&list,3);
  List_int::insert_back(&list,4);

  list->printList(); // prints 0,1,2,3,4 
  cout<<"##########"<<endl;

  List_int * current = list;
  List_int * previous = NULL;
  while (current->next) // loop to last element while preserving previous element
      previous = current, current = current->next;
  current = List_int::removeItem(&list, previous, current); // removeItem returns pointer to next element in list (since we are removing last element -> NULL)
  list->printList(); // prints 0,1,2,3

  for (current = list, previous = NULL; current; previous = current, current = current->next, delete previous); //clear list

  return 0;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment