Advertisement
Guest User

Untitled

a guest
Feb 21st, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.13 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct node{
  5.     int data;
  6.     struct node * next;
  7. } node_t;
  8.  
  9. typedef struct linkedlist{
  10.     int size;
  11.     struct node * list;
  12. } linkedlist_t;
  13.  
  14. //& means as a part of the parameter indicates pass by reference
  15. void initiliaze(linkedlist_t* list){
  16.     list->size = 0; //No elements in the list
  17.     list->list = NULL; //list is empty
  18. }
  19.  
  20. void addnode(linkedlist_t* currentlist, int newdata){
  21.     //Create a pointer to a new nde and allocate space on the heap for the new node
  22.     //Java: node new = new node();
  23.    
  24.     node_t* newnode = (node_t*)malloc(sizeof(node_t));
  25.     newnode->next = currentlist->list;
  26.     newnode->data = newdata;
  27.     currentlist->list = newnode;
  28.     currentlist-> size++;
  29. }
  30.  
  31. void print(linkedlist_t* currentlist){
  32.     node_t* temp = currentlist -> list;
  33.     while(temp != NULL){
  34.         printf("%d ", temp -> data);
  35.         temp = temp-> next;
  36.     }
  37. }
  38.  
  39.  
  40.  
  41.  
  42.  
  43. int main(void){
  44.    
  45.     linkedlist_t mylist;
  46.     initiliaze(&mylist); //this will hand myList into the initialize function instead of creating a copy
  47.     addnode(&mylist, 1);
  48.     addnode(&mylist, 55);
  49.     addnode(&mylist, 42);
  50.     print(&mylist);
  51.     return 0;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement