Code - R4

Nature of Code 之 4 - Particle. Particle System uses list . O_o

#ifndef __PARTICLE_SYSTEM_H__
#define __PARTICLE_SYSTEM_H__
#include "particle.h"
#include <stdio.h>

typedef struct PtlSystem {
  Particle *Head;
  float x, y;
  void (*Add)(struct PtlSystem *);
  int (*Len)(struct PtlSystem *);
  void (*Delete)(struct PtlSystem *);
  void (*Destroy)(struct PtlSystem *);
} PtlSystem;

static int _length_of_list(PtlSystem *ls) {
  Particle *current = ls->Head;
  int iret = 0;
  if (ls->Head == NULL)
    return iret;

  for (; current != NULL; current = current->next) {
    iret++;
  }
  return iret;
}

static void _add_particle(PtlSystem *ls) {
  Particle *p = NULL;
  if (ls->Head == NULL) {
    ls->Head = NewParticle(ls->x, ls->y);
  } else {
    p = ls->Head;
    while (p->next != NULL) {
      p = p->next;
    }
    p->next = NewParticle(ls->x, ls->y);
  }
}

static void _delete_particle(PtlSystem *ls) {
  Particle *current = ls->Head;
  Particle *previous = current;
  while (current != NULL) {
    if (current->IsDead(current)) {
      previous->next = current->next;
      if (current == ls->Head)
        ls->Head = current->next;
      current->Destroy(current);
      return;
    }
    previous = current;
    current = current->next;
  }
}
static void _destroy_PtrSystem(PtlSystem *list) {
  Particle *current = list->Head;
  Particle *next = current;
  while (current != NULL) {
    next = current->next;
    current->Destroy(current);
    current = next;
  }
  free(list);
}

PtlSystem *NewPtlSystem(float x, float y) {
  PtlSystem *ptlsys = (PtlSystem *)malloc(sizeof(PtlSystem));
  ptlsys->x = x;
  ptlsys->y = y;
  ptlsys->Head = NULL;
  ptlsys->Add = &_add_particle;
  ptlsys->Len = &_length_of_list;
  ptlsys->Delete = &_delete_particle;
  ptlsys->Destroy = &_destroy_PtrSystem;
  return ptlsys;
}

#endif

完整的在這裏

c  program  sgi 

See also