logo

Atravesando en una lista enlazada individualmente

Atravesar es la operación más común que se realiza en casi todos los escenarios de listas enlazadas individualmente. Atravesar significa visitar cada nodo de la lista una vez para realizar alguna operación en él. Esto se hará utilizando las siguientes declaraciones.

 ptr = head; while (ptr!=NULL) { ptr = ptr -> next; } 

Algoritmo

    PASO 1:ESTABLECER PTR = CABEZAPASO 2:SI PTR = NULO

    ESCRIBA 'LISTA VACÍA'
    IR AL PASO 7
    FIN DE SI

    ETAPA 4:REPITE LOS PASOS 5 Y 6 HASTA PTR != NULLPASO 5:IMPRIMIR PTR→ DATOSPASO 6:PTR = PTR → SIGUIENTE

    [FIN DEL BUCLE]

    PASO 7:SALIDA

función C

 #include #include void create(int); void traverse(); struct node { int data; struct node *next; }; struct node *head; void main () { int choice,item; do { printf('
1.Append List
2.Traverse
3.Exit
4.Enter your choice?'); scanf('%d',&choice); switch(choice) { case 1: printf('
Enter the item
'); scanf('%d',&item); create(item); break; case 2: traverse(); break; case 3: exit(0); break; default: printf('
Please enter valid choice
'); } }while(choice != 3); } void create(int item) { struct node *ptr = (struct node *)malloc(sizeof(struct node *)); if(ptr == NULL) { printf('
OVERFLOW
'); } else { ptr->data = item; ptr->next = head; head = ptr; printf('
Node inserted
'); } } void traverse() { struct node *ptr; ptr = head; if(ptr == NULL) { printf('Empty list..'); } else { printf('printing values . . . . .
'); while (ptr!=NULL) { printf('
%d',ptr->data); ptr = ptr -> next; } } } 

Producción

 1.Append List 2.Traverse 3.Exit 4.Enter your choice?1 Enter the item 23 Node inserted 1.Append List 2.Traverse 3.Exit 4.Enter your choice?1 Enter the item 233 Node inserted 1.Append List 2.Traverse 3.Exit 4.Enter your choice?2 printing values . . . . . 233 23