[ create a new paste ] login | about

Link: http://codepad.org/osqIJ92M    [ raw code | output | fork ]

C, pasted on Oct 16:
#include <stdio.h>
#include <stdlib.h>

#define xmalloc malloc
#define xfree free

struct node {
  struct node *next;
};

void add_node(struct node **p) {
  struct node *q;
  if (p == NULL)
    return;
  if (*p == NULL) {
    if ((q = xmalloc(sizeof(struct node))) == NULL)
      return;
    q->next = NULL;
    *p = q;
    return;
  }
  add_node(&((*p)->next));
}

void concat(struct node *p, struct node *q) {
  if (p == NULL || q == NULL)
    return;
  for (;p->next != NULL; p = p->next)
    ;
  p->next = q;
}

int length(struct node *p) {
  if (p == NULL)
    return 0;
  else
    return length(p->next) + 1;
}

void delete(struct node **p) {
  if (p == NULL)
    return;
  if (*p == NULL)
    return;
  delete(&((*p)->next));
  xfree(*p);
  *p = NULL;
}

#define N1 200
#define N2 300
int main() {
  int i;
  struct node *p, *q;
  p = q = NULL;
  for (i = 0; i < N1; i++)
    add_node(&p);
  for (i = 0; i < N2; i++)
    add_node(&q);
  printf("p: %d\n", length(p));
  printf("q: %d\n", length(q));
  concat(p, q);
  printf("p + q: %d\n", length(p));
  delete(&p);
  printf("after delete: %d\n", length(p));
  return 0;
}
/* end */


Output:
1
2
3
4
p: 200
q: 300
p + q: 500
after delete: 0


Create a new paste based on this one


Comments: