logo

Kretanje u pojedinačno povezanom popisu

Kretanje je najčešća operacija koja se izvodi u gotovo svakom scenariju pojedinačno povezanog popisa. Kretanje znači posjetiti svaki čvor popisa jednom kako bi se na njemu izvršila neka operacija. To će se učiniti korištenjem sljedećih izjava.

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

Algoritam

    KORAK 1:POSTAVITE PTR = GLAVAKORAK 2:AKO je PTR = NULL

    NAPIŠI 'PRAZAN POPIS'
    IDITE NA KORAK 7
    KRAJ AKO

    4. KORAK:PONAVLJAJTE KORAKE 5 I 6 SVE DOK PTR != NULLKORAK 5:ISPIS PTR→ PODACIKORAK 6:PTR = PTR → DALJE

    [KRAJ PETLJE]

    KORAK 7:IZLAZ

C funkcija

 #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; } } } 

Izlaz

 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