mieczyk - 05-21-2007 19:00:39

USUWANIE PODANEGO ELEMENTU Z LISTY

Kod:

#include <stdlib.h>
#include <stdio.h>

typedef struct element element;

struct element 
{
       int x;
       struct element *next;
};


void wyswietl(element *lista)
{
     while (lista)
     {
        printf("[%d] -> ", lista->x);
        lista=lista->next;
     }
     printf("[NULL]");
}


void usun(element **lista, int y)
{
     element *e, *tmp, *tmp1;
     
     e=*lista;
     tmp1=*lista;
     tmp=tmp1; 
    
     while (tmp1)
     {

         if (*lista == NULL)
         {
             printf("LISTA PUSTA");
             getchar();
             getchar();
             exit (0);
          }  
     
          if ((*lista)->x == y)
         {
             e=(*lista)->next;
             free(*lista);
             *lista=e;
         }
         else
        {   
            if (tmp1->x == y)
           {
               tmp->next = tmp1->next;
               free(tmp1);
               tmp1=tmp;
           }
           
           tmp=tmp1;
           tmp1=tmp1->next;
       }
     } 
}


main()
{
      element *lista, *e;
      int i,y;
      
      lista=NULL;
      for(i=0; i<5; i++)
      {
          e=malloc(sizeof(element));
          scanf("%i", &e->x);
          
          e->next=lista;
          lista=e;
      }
      
      wyswietl(lista);
      printf("\n\npodaj co chcesz usunac\n");   
      scanf("%i", &y);
      usun(&lista,y);    
      wyswietl(lista);

      getchar();
      getchar();            
}

Uwaga!

Wypada jeszcze po sobie posprzątać :). To znaczy na końcu należy wyczyścić całą listę !


Algorytm created by   mmiles and mieczyk Company :)

GotLink.pl