Advertisement
Guest User

Lista simples

a guest
May 24th, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.04 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct item {
  5.     char content;
  6.     struct item* next;
  7. } item;
  8.  
  9. void addItem(item* first, char content){    
  10.     item* act;
  11.  
  12.     if(first == NULL){
  13.         first = malloc(sizeof(item));
  14.         first->content = content;
  15.         first->next = NULL;
  16.     }else{
  17.         act = first;
  18.         //Percorre a lista até o último item
  19.         while(act->next != NULL)
  20.             act = act->next;
  21.         act->next = malloc(sizeof(item));
  22.         act->next->content = content;
  23.         act->next->next = NULL;
  24.     }
  25. }
  26.  
  27. void print(item* first){
  28.     item* temp = first;
  29.  
  30.     while(temp != NULL){
  31.         printf("%c", temp->content);
  32.         temp = temp->next;
  33.     }
  34. }
  35.  
  36. int main(){
  37.     item* first;
  38.     first = NULL;
  39.  
  40.     //Adicionar primeiro item pelo main
  41.     /*first = malloc(sizeof(item));
  42.     first->content = 'a';
  43.     first->next = NULL;*/
  44.  
  45.     addItem(first, 'b');
  46.     addItem(first, 'c');
  47.     addItem(first, 'd');
  48.  
  49.     print(first);
  50.  
  51.     printf("\n");
  52.     return 0;
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement