En builder....

Estado
Cerrado para nuevas respuestas.

ODDG

LANero Fundador
Lanero VIP
13 Abr 2001
1,548
Necesito un ejemplo sencillo de una lista ligada simple en C++ Builder, aguien puede colaborarme?
 
Yo tengo por ahi una medio aplicación toda ficti de listas doblemente enlazadas segun creo.., la voy a buscar y la pongo...
 
Bueno para construir listas simplemente ligadas necesitamos construir un estructura autoreferenciada que debe llevar un (o mas) campo(s), que debe(n) contener el (los) dato(s), y otro campo que es el que contiene la liga, es decir, el campo con el que vamos a enlazar los datos. aqui te muestro un ejemplo sencillo que ilustra esta situacion, lee, analiza el codigo, si tienes alguna duda con gusto te estare colaborando (tomado del libro Deitel & Deitel, Como Programar en C/C++).

PD: estructura autoreferenciada: Una estructura autoreferenciada contiene un miembro de apuntador que aopunta a una estructura del mismo tipo de estructura. por ejemplo:

struct nodo{
int dato;
struct nodo *siguiente;
}


Código:
/* Fig. 12.3: fig12_03.c
   Operating and maintaining a list */
#include <stdio.h>
#include <stdlib.h>

struct listNode {   /* self-referential structure */
   char data;
   struct listNode *nextPtr;
};

typedef struct listNode ListNode;
typedef ListNode *ListNodePtr;

void insert( ListNodePtr *, char );
char delete( ListNodePtr *, char );
int isEmpty( ListNodePtr );
void printList( ListNodePtr );
void instructions( void );

int main()
{
   ListNodePtr startPtr = NULL;
   int choice;
   char item;

   instructions();  /* display the menu */
   printf( "? " );
   scanf( "%d", &choice );

   while ( choice != 3 ) {

      switch ( choice ) {
         case 1:
            printf( "Enter a character: " );
            scanf( "\n%c", &item );
            insert( &startPtr, item );
            printList( startPtr );
            break;
         case 2:
            if ( !isEmpty( startPtr ) ) {
               printf( "Enter character to be deleted: " );
               scanf( "\n%c", &item );

               if ( delete( &startPtr, item ) ) {
                  printf( "%c deleted.\n", item );
                  printList( startPtr );
               }
               else
                  printf( "%c not found.\n\n", item );
            }
            else
               printf( "List is empty.\n\n" );

            break;
         default:
            printf( "Invalid choice.\n\n" );
            instructions();
            break;
      }

      printf( "? " );
      scanf( "%d", &choice );
   }

   printf( "End of run.\n" );
   return 0;
}

/* Print the instructions */
void instructions( void )
{
   printf( "Enter your choice:\n"
          "   1 to insert an element into the list.\n"
          "   2 to delete an element from the list.\n"
          "   3 to end.\n" );
}

/* Insert a new value into the list in sorted order */
void insert( ListNodePtr *sPtr, char value )
{
   ListNodePtr newPtr, previousPtr, currentPtr;

   newPtr = malloc( sizeof( ListNode ) );

   if ( newPtr != NULL ) {     /* is space available */
      newPtr->data = value;
      newPtr->nextPtr = NULL;

      previousPtr = NULL;
      currentPtr = *sPtr;

      while ( currentPtr != NULL && value > currentPtr->data ) {
         previousPtr = currentPtr;          /* walk to ...   */
         currentPtr = currentPtr->nextPtr;  /* ... next node */
      }

      if ( previousPtr == NULL ) {
         newPtr->nextPtr = *sPtr;
         *sPtr = newPtr;
      }
      else {
         previousPtr->nextPtr = newPtr;
         newPtr->nextPtr = currentPtr;
      }
   }
   else
      printf( "%c not inserted. No memory available.\n", value );
}

/* Delete a list element */
char delete( ListNodePtr *sPtr, char value )
{
   ListNodePtr previousPtr, currentPtr, tempPtr;

   if ( value == ( *sPtr )->data ) {
      tempPtr = *sPtr;
      *sPtr = ( *sPtr )->nextPtr;  /* de-thread the node */
      free( tempPtr );             /* free the de-threaded node */
      return value;
   }
   else {
      previousPtr = *sPtr;
      currentPtr = ( *sPtr )->nextPtr;

      while ( currentPtr != NULL && currentPtr->data != value ) {
         previousPtr = currentPtr;          /* walk to ...   */
         currentPtr = currentPtr->nextPtr;  /* ... next node */
      }

      if ( currentPtr != NULL ) {
         tempPtr = currentPtr;
         previousPtr->nextPtr = currentPtr->nextPtr;
         free( tempPtr );
         return value;
      }
   }

   return '\0';
}

/* Return 1 if the list is empty, 0 otherwise */
int isEmpty( ListNodePtr sPtr )
{
   return sPtr == NULL;
}

/* Print the list */
void printList( ListNodePtr currentPtr )
{
   if ( currentPtr == NULL )
      printf( "List is empty.\n\n" );
   else {
      printf( "The list is:\n" );

      while ( currentPtr != NULL ) {
         printf( "%c --> ", currentPtr->data );
         currentPtr = currentPtr->nextPtr;
      }

      printf( "NULL\n\n" );
   }
}
 
ya para listas doblemente ligadas, solo le le agrega un campo mas a la estructura para crear los campos liga izquierda y liga derecha.
 
Muchas gracias victor, pero verdaderamente ese código no funciona en C++ Builder.

Para el código:

struct nodo{
int dato;
struct nodo *siguiente;
}

como se pide memoria para el primer nodo?
algo como así?

newPtr = malloc( sizeof( ListNode ) );

Exactamente es esto lo que no me funciona en builder...
Por favor, un ejemplo pequeño y sencillo.
 
En Ansi C, la asignacion dinamica de memoria por lo general se lleva a cabo con las funciones estandar malloc y free, en c++ se usan los operadores new y delete.

se pide memoria con new ListNode;

para ello debes incluir iostream.h, ahhh entonces debemos modificar la funcion llamada delete, porque el compilador la confunde con el operador delete, la podemos rebonmbrar por ejemplo con borrar.

bueno aqui coloco el codigo modificado:

Código:
#include <stdio.h>
#include <stdlib.h>
#include <iostream.h>

struct listNode {   /* self-referential structure */
   char data;
   struct listNode *nextPtr;
};

typedef struct listNode ListNode;
typedef ListNode *ListNodePtr;

void insert( ListNodePtr *, char );
char borrar( ListNodePtr *, char );
int isEmpty( ListNodePtr );
void printList( ListNodePtr );
void instructions( void );

int main()
{
   ListNodePtr startPtr = NULL;
   int choice;
   char item;

   instructions();  /* display the menu */
   printf( "? " );
   scanf( "%d", &choice );

   while ( choice != 3 ) {

      switch ( choice ) {
	 case 1:
	    printf( "Enter a character: " );
	    scanf( "\n%c", &item );
	    insert( &startPtr, item );
	    printList( startPtr );
	    break;
	 case 2:
	    if ( !isEmpty( startPtr ) ) {
	       printf( "Enter character to be deleted: " );
	       scanf( "\n%c", &item );

	       if ( borrar( &startPtr, item ) ) {
		  printf( "%c deleted.\n", item );
		  printList( startPtr );
	       }
	       else
		  printf( "%c not found.\n\n", item );
	    }
	    else
	       printf( "List is empty.\n\n" );

	    break;
	 default:
	    printf( "Invalid choice.\n\n" );
	    instructions();
	    break;
      }

      printf( "? " );
      scanf( "%d", &choice );
   }

   printf( "End of run.\n" );
   return 0;
}

/* Print the instructions */
void instructions( void )
{
   printf( "Enter your choice:\n"
	  "   1 to insert an element into the list.\n"
	  "   2 to delete an element from the list.\n"
	  "   3 to end.\n" );
}

/* Insert a new value into the list in sorted order */
void insert( ListNodePtr *sPtr, char value )
{
   ListNodePtr newPtr, previousPtr, currentPtr;

   newPtr = new ListNode;

   if ( newPtr != NULL ) {     /* is space available */
      newPtr->data = value;
      newPtr->nextPtr = NULL;

      previousPtr = NULL;
      currentPtr = *sPtr;

      while ( currentPtr != NULL && value > currentPtr->data ) {
	 previousPtr = currentPtr;          /* walk to ...   */
	 currentPtr = currentPtr->nextPtr;  /* ... next node */
      }

      if ( previousPtr == NULL ) {
	 newPtr->nextPtr = *sPtr;
	 *sPtr = newPtr;
      }
      else {
	 previousPtr->nextPtr = newPtr;
	 newPtr->nextPtr = currentPtr;
      }
   }
   else
      printf( "%c not inserted. No memory available.\n", value );
}

/* Delete a list element */
char borrar( ListNodePtr *sPtr, char value )
{
   ListNodePtr previousPtr, currentPtr, tempPtr;

   if ( value == ( *sPtr )->data ) {
      tempPtr = *sPtr;
      *sPtr = ( *sPtr )->nextPtr;  /* de-thread the node */
      delete tempPtr;             /* free the de-threaded node */
      return value;
   }
   else {
      previousPtr = *sPtr;
      currentPtr = ( *sPtr )->nextPtr;

      while ( currentPtr != NULL && currentPtr->data != value ) {
	 previousPtr = currentPtr;          /* walk to ...   */
	 currentPtr = currentPtr->nextPtr;  /* ... next node */
      }

      if ( currentPtr != NULL ) {
	 tempPtr = currentPtr;
	 previousPtr->nextPtr = currentPtr->nextPtr;
	 delete tempPtr;
	 return value;
      }
   }

   return '\0';
}

/* Return 1 if the list is empty, 0 otherwise */
int isEmpty( ListNodePtr sPtr )
{
   return sPtr == NULL;
}

/* Print the list */
void printList( ListNodePtr currentPtr )
{
   if ( currentPtr == NULL )
      printf( "List is empty.\n\n" );
   else {
      printf( "The list is:\n" );

      while ( currentPtr != NULL ) {
	 printf( "%c --> ", currentPtr->data );
	 currentPtr = currentPtr->nextPtr;
      }

      printf( "NULL\n\n" );
   }
}
 
Si funciona, yo tambien hice mis listas basado en esos ejemplos, mañana pongo el codigo fuente..

PD: Ya vieron el BuilderC++ 6?, yo lo baje, me parece muy bacano que le mejoraron el inteligent science creo que asi se llama, o el autocompletar.., ya no se demora tanto como el 5...
 
No sabia que las listas enlazadas las llamaban también listas ligadas, me suena tan comico :)
 
Tengo por ahi algo de listas y colas, basados para Builder, pero si puedes probar los codigos enviados pos los demas compañeros, solo ke en modo consola.
Prometo subir mis codigos para la prox.
 
Estado
Cerrado para nuevas respuestas.

Los últimos temas