Skip to content

Instantly share code, notes, and snippets.

@aaronryank
Created November 30, 2016 05:26
Show Gist options
  • Save aaronryank/07904a0b42b268e0bd587ca5d9ee32ed to your computer and use it in GitHub Desktop.
Save aaronryank/07904a0b42b268e0bd587ca5d9ee32ed to your computer and use it in GitHub Desktop.
// retrieve 'https://gist.githubusercontent.com/aaronryank/28e6786b812ffa7976260aeb1ec1851b/raw/bf88b6c195a5486a98dec294d4ee887e18aa061b/node.h' before compiling
#include "node.h"
#include <stdio.h>
#include <stdlib.h>
void print_list(node_t * head) {
node_t * current = head;
while (current != NULL) {
printf("%ld\n", current->val);
current = current->next;
}
}
void push(node_t * head, long val) {
node_t * current = head;
while (current->next != NULL) {
current = current->next;
}
/* now we can add a new variable */
current->next = malloc(sizeof(node_t));
current->next->val = val;
current->next->next = NULL;
}
int pop(node_t ** head) {
int retval = -1;
node_t * next_node = NULL;
if (*head == NULL) {
return -1;
}
next_node = (*head)->next;
retval = (*head)->val;
free(*head);
*head = next_node;
return retval;
}
int remove_last(node_t * head) {
int retval = 0;
/* if there is only one item in the list, remove it */
if (head->next == NULL) {
retval = head->val;
free(head);
return retval;
}
/* get to the last node in the list */
node_t * current = head;
while (current->next->next != NULL) {
current = current->next;
}
/* now current points to the last item of the list, so let's remove current->next */
retval = current->next->val;
free(current->next);
current->next = NULL;
return retval;
}
int remove_by_index(node_t ** head, int n) {
int j, i = 0;
long retval = -1;
node_t * current = *head;
node_t * temp_node = NULL;
if (n == 0) {
return pop(head);
}
for (j = 0; j < n-1; j++) {
if (current->next == NULL) {
return -1;
}
current = current->next;
}
temp_node = current->next;
retval = temp_node->val;
current->next = temp_node->next;
free(temp_node);
return retval;
}
@aaronryank
Copy link
Author

Simple stack manipulation program

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment