Advertisement
Guest User

Untitled

a guest
Feb 18th, 2020
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.91 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. struct data {
  5.     int value;
  6.     struct data *next; // define as pointer, why dont we just type data *next?
  7. } *head, *node; // init as a pointer
  8.  
  9. void push(int x) {
  10.     // when push is called, malloc will allocated new memory block!
  11.     node = (struct data *) malloc(sizeof(struct data));
  12.     node->value = x;
  13.    
  14.     if (head == NULL) {
  15.         head = node;
  16.         head->next = NULL;
  17.     } else {
  18.         // save the newer node as head, and set older node->next to head
  19.         node->next = head;
  20.         head = node;
  21.     }
  22. }
  23.  
  24. void view() {
  25.    
  26. }
  27.  
  28. int main() {
  29.     // because *head is a pointer, its should contain memory address (& in primitive data types)
  30.     // head = (struct data *) malloc(sizeof(struct data)); // same concept as (int *) malloc(sizeof (int))
  31.     // head->value = 5; // access pointer struct attr using (->) instead of (.)
  32.    
  33.     push(50);
  34.     push(25);
  35.    
  36.     printf("%d\n", head->value);
  37.    
  38.    
  39.    
  40.     return 0;
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement