Skip to content

Instantly share code, notes, and snippets.

@vinitkumar
Created February 27, 2017 18:20
Show Gist options
  • Select an option

  • Save vinitkumar/6dc8e7ce25fc3d447af89289f941ab14 to your computer and use it in GitHub Desktop.

Select an option

Save vinitkumar/6dc8e7ce25fc3d447af89289f941ab14 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int val;
struct node *next;
} node_t;
// pop will return the element that is popped and moves the head
// to the next head
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_by_value(node_t ** head, int val) {
node_t *previous, *current;
if (*head == NULL) {
return -1;
}
if ((*head)->val == val) {
return pop(head);
}
previous = current = (*head)->next;
while(current) {
if (current->val == val) {
previous->next = current->next;
free(current);
return val;
}
previous = current;
current = current->next;
}
return -1;
}
void print_list(node_t *head) {
node_t *current = head;
while (current != NULL) {
printf("%d\n", current->val);
current = current->next;
}
}
int main() {
node_t * test_list = malloc(sizeof(node_t));
test_list->val = 1;
test_list->next = malloc(sizeof(node_t));
test_list->next->val = 2;
test_list->next->next= NULL;
printf("Printing the linked list\n");
print_list(test_list);
remove_by_value(&test_list, 1);
printf("Printing the linked list again\n");
print_list(test_list);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment