Skip to content

Instantly share code, notes, and snippets.

@dstdfx
Created February 16, 2018 19:57
Show Gist options
  • Select an option

  • Save dstdfx/86e188240f9a4ba028d362c6e098549f to your computer and use it in GitHub Desktop.

Select an option

Save dstdfx/86e188240f9a4ba028d362c6e098549f to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int key;
struct node *next;
} node_t;
// Initialize first element of the list
node_t *init_st(int value){
node_t *list = (node_t*)malloc(sizeof(node_t));
if (list == NULL){
printf("I CANT!\n");
return NULL;
}
list->key = value;
list->next = NULL;
return list;
}
int is_empty(node_t *list){
return list == NULL ? 1 : 0;
}
// Add element to the end of the list
void push(node_t *list, int value){
node_t *current = list;
// Iterate over list to find last
while (current->next != NULL){
current = current->next;
}
// Allocate memory for new node
current->next = (node_t*)malloc(sizeof(node_t));
if (current->next == NULL){
printf("Can't allocate a memory for new node.\n");
} else {
// Insert value and next node
current->next->key = value;
current->next->next = NULL;
printf("Successfully pushed: %d\n", value);
}
}
int main(){
// Init list, first element with key 1
node_t *head = init_st(1);
push(head, 2);
push(head, 3);
free(head);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment