Advertisement
Guest User

Untitled

a guest
May 21st, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.27 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3.  
  4. struct node {
  5.   int value;
  6.   struct node *next;
  7. };
  8.  
  9. typedef struct node *tlista;
  10.  
  11. void print_list(tlista head) {
  12.   tlista current = head;
  13.  
  14.   if(current == NULL){
  15.     printf("NULL\n");
  16.   }
  17.  
  18.   while (current != NULL) {
  19.     printf("%d -> ", current->value);
  20.     current = current->next;
  21.     if(!current){
  22.       printf("NULL\n");
  23.     }
  24.   }
  25.   printf("\n");
  26. }
  27.  
  28. void pushLast(tlista head){
  29.   tlista current = head;
  30.   while (current->next != NULL){
  31.     current = current->next;
  32.   }
  33.  
  34.   current->next = head;
  35. }
  36.  
  37. void push(tlista head, int val) {
  38.   tlista current = head;
  39.   while (current->next != NULL) {
  40.     current = current->next;
  41.   }
  42.  
  43.   /* now we can add a new variable */
  44.   current->next = (tlista)malloc(sizeof(struct node));
  45.   current->next->value = val;
  46.   current->next->next = NULL;
  47. }
  48.  
  49. void free_list(tlista head) {
  50.   tlista tmp;
  51.  
  52.   while (head != NULL) {
  53.     tmp = head;
  54.     head = head->next;
  55.     free(tmp);
  56.   }
  57. }
  58.  
  59. int main(){
  60.   tlista l1 = NULL;
  61.   l1 = malloc(sizeof(struct node));
  62.   l1->value = 4;
  63.   l1->next = NULL;
  64.  
  65.   push(l1, 6);
  66.   push(l1, 2);
  67.   push(l1, 6);
  68.   push(l1, 7);
  69.   push(l1, 9);
  70.   pushLast(l1);
  71.  
  72.   printf("lista1: ");
  73.   print_list(l1);
  74.  
  75.   free(l1);
  76.  
  77.   return 0;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement