Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #define DEBUG(P) printf("%d\n", (P)->val);
- //Linked list.
- struct node {
- int val;
- struct node *next;
- };
- void init_head(struct node **head) {
- (*head)->val = 0;
- (*head)->next = NULL;
- }
- void add_first(struct node **head, int val) {
- struct node *node_t = (struct node *)malloc(sizeof(struct node));
- node_t->val = val;
- node_t->next = *head;
- *head = node_t;
- }
- void add_last(struct node *head, int val) {
- struct node *ptr = head;
- while (ptr->next != NULL)
- ptr = ptr->next;
- ptr->next = (struct node *)malloc(sizeof(struct node));
- ptr->next->val = val;
- ptr->next->next = NULL;
- }
- void print_list(struct node *head) {
- struct node *ptr = head;
- while (ptr != NULL) {
- printf("Value: %d\n", ptr->val);
- ptr = ptr->next;
- }
- }
- void delete_first_node(struct node **head) {
- struct node *ptr = *head;
- *head = ptr->next;
- free(ptr);
- }
- void delete_last_node(struct node *head) {
- struct node *ptr = head;
- struct node *t = NULL;
- while (ptr->next != NULL) {
- t = ptr;
- ptr = ptr->next;
- }
- free(ptr);
- t->next = NULL;
- }
- void free_mem_list(struct node *head) {
- struct node *ptr_node;
- while ((ptr_node = head) != NULL) {
- head = head->next;
- free(ptr_node);
- }
- }
- void remove_node(struct node **head, int _val) {
- struct node *ptr = *head;
- struct node *temp_ptr = ptr;
- while (ptr != NULL) {
- if (ptr->val == _val) {
- if (ptr == *head) {
- temp_ptr = *head;
- ptr = ptr->next;
- *head = (*head)->next;
- free(temp_ptr);
- temp_ptr = ptr;
- } else if (ptr->next == NULL) {
- delete_last_node(*head);
- return;
- } else {
- temp_ptr->next = ptr->next;
- free(ptr);
- ptr = temp_ptr->next; // RESTORE PTR , (IS THE RIGHT WAY(?))
- }
- }else{
- temp_ptr = ptr;
- ptr = ptr->next;
- }
- }
- }
- int main(int argc, char **argv) {
- struct node *head = (struct node *)malloc(sizeof(struct node));
- init_head(&head);
- add_first(&head, 15);
- add_last(head, 13);
- add_last(head, 15);
- remove_node(&head, 15);
- print_list(head);
- free_mem_list(head);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement