All pastes #46807 Raw Edit

awan

public text v1 · immutable
#46807 ·published 2006-03-24 12:20 UTC
rendered paste body
#include <stdio.h>
#include <stdlib.h>

struct linked_list {
    int data;
    struct linked_list * next;
};

typedef struct linked_list item;

void add(item **p, int data) 
{
  if (!(*p)) 
     {
         (*p) = (item *)malloc(sizeof(item));
         (*p)->next = NULL;
         (*p)->data = data;
     }
  else
     add(&(*p)->next,data);
}

void print(item *p)
{
   while (p) 
     {
      printf("%d\n", p->data);
      p=p->next;
     }

}

char _delete(item **p)
{
  item *ptr = *p;
  if (!(*p)) return '\0';
  if (*p == ((*p)->next))
   {
    ptr = (*p);
    *p = NULL;
   } else {
   ptr = (*p)->next; 
   }
   free(ptr);
}

char delsearch(item **p, int e)
{
  item *tmp = (*p);
  if (!(*p)) return '\0';
  while (((tmp->next) != (*p)) && ((tmp->next->data) != e))
    tmp = tmp->next;
  if ((tmp->next->data) !=e)
    if (tmp == (*p)->next) 
     *p = NULL;
   else *p = tmp;
  return _delete(&tmp);
}

int main(int argc, char *argv[])
{
  item *ptr=NULL;
  int i;
  for (i=1; i<=10; i++)
   {
    add(&ptr,i);
   }
  delsearch(&ptr,5);
  print(ptr);
  return EXIT_SUCCESS;
}