/* lista-2.c - Exemplo de lista duplamente encadeada

  Copyright 2009 - Francisco Jose Monaco

  This program is Free Software and can be distributed under the GNU GPL v3
  as found in www.gnu.org/licenses/gpl.txt

*/


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

/* Para acrescentar um no no final da lista, ou percorremos a lista
  toda procurando pelo ultimo no, ou acrescentamos um ponteiro para
  o ultimo no no cabecalho.  Em qualquer caso, precisaremos tambem
  de um ponteiro para o no anterior a ultimo.*/

typedef struct no no_t;
struct no
{
  int valor;
  struct no * proximo;
  struct no * anterior;
};

typedef struct head head_t;
struct head
{
  struct no * primeiro;
  struct no * ultimo;
  int tamanho;

};

void mostra(head_t *h)
{
  no_t *n;
 
  n = h->primeiro;
  while (n != NULL)
    {
      printf (" %d", n->valor);
      n = n->proximo;
    }
  printf ("  Primeiro %d, ultimo %d\n",
  h->primeiro->valor, h->ultimo->valor);


 
}

no_t * add_no_inicio (head_t *h, int v)
{
  no_t * no;

  no = (no_t*) malloc (sizeof(no_t)); /* Criando no. */

  no->valor = v;

  no->proximo = h->primeiro;

  no->anterior = NULL;

  if (h->ultimo == NULL)
    h->ultimo = no;
  else
    h->primeiro->anterior = no;
 
  h->primeiro = no;

  h->tamanho++;

  return no;
}

void del_no_inicio (head_t *h)
{
  no_t *no;

  no = h->primeiro;
  h->primeiro = no->proximo; 

  if (h->ultimo == no)
    h->ultimo = NULL;

  h->tamanho--;

  free(no);
 
}

no_t * add_no_fim (head_t *h, int v)
{
  no_t * no;

  no = (no_t*) malloc (sizeof(no_t)); /* Criando no. */

  no->valor = v;

  no->proximo = NULL;

  if (h->primeiro == NULL)
    h->primeiro = no;
  else
    h->ultimo->proximo = no;
 
  h->ultimo = no;

  h->tamanho++;

  return no;
}

/*

no_t * del_no_fim (head_t *h, int v)
{
  no_t *no;

  no = h->ultimo;
  h->ultimo =

  if (h->ultimo == no)
    h->ultimo = NULL;

  h->tamanho--;

  free(no);
}

*/

int main(void)
{

  head_t * list_head;

  /* Criando lista (vazia). */

  list_head = (head_t*) malloc (sizeof(head_t));
 
  list_head->primeiro = NULL;
  list_head->ultimo = NULL;
  list_head->tamanho = 0;

  /* Adicionando um no. */
 
  add_no_inicio (list_head, 30);
  add_no_inicio (list_head, 20);
  add_no_inicio (list_head, 15);
  add_no_inicio (list_head, 10);

  mostra (list_head);

  add_no_fim (list_head, 35);

  mostra (list_head);

  del_no_inicio (list_head);

  mostra (list_head);

  return EXIT_SUCCESS;
}
Última atualização: quinta, 8 outubro 2009, 22:15