#include <stdlib.h>
#include <stdio.h>
typedef struct {
int val;
struct node *next;
} node;
node* create_node ( int x ) {
node* n = malloc (sizeof(node) );
if (n==NULL) return NULL;
n->val = x;
n->next = NULL;
return n;
}
void print_list ( node * h) ;
void add_node ( node** h, int v) ;
int remove_front (node ** h);
int main () {
node * head = NULL;
int v = 10;
for (int i = 0; i < 5; i++) {
add_node( &head , i * v);
}
print_list(head);
while (head)
printf("removed: %d\n", remove_front(&head));
}
void print_list( node * h) {
if (h == NULL) return;
node * n = h;
while (n != NULL) {
printf("%d, ", n->val);
n = n->next;
}
printf("\n");
}
void add_node( node** h, int v ) {
if (h==NULL) return; //invalid list
node * n = create_node(v);
if (*h == NULL ) { //empty list
*h = n;
return;
}
//find the end of the list
node * cur = *h;
while (cur->next != NULL) {
cur = cur->next;
}
cur->next = n;
}
int remove_front ( node ** h){
if (h==NULL) return -1; //invalid list
if (*h == NULL ) { //empty list
return -1;
}
//get the value from the first node and delete that node
node * n = *h;
int val = n->val;
*h = (*h)->next;
free(n);
return val;
}
Created
May 22, 2020 12:41
-
-
Save joannakl/675bb0d5ed842cf5844d8f86c1fa7a34 to your computer and use it in GitHub Desktop.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment