Untitled

 avatar
unknown
plain_text
a year ago
2.0 kB
3
Indexable
#include <stdio.h>
#include <stdlib.h>

struct node {
    int data;
    struct node *next;
};

// Provided Functions
struct node *create_node(int data);
struct node *insert_at_head(struct node *head, int data);
void print_list(struct node *head);

// Your functions
struct node *delete_negatives(struct node *head);

int main(void) {

    struct node *head = insert_at_head(NULL, 6);
    head = insert_at_head(head, -2);
    head = insert_at_head(head, -4);
    
    print_list(head);
    head = delete_negatives(head);
    print_list(head);
    
    return 0;
}

// Mallocs a new node and returns a pointer to it
struct node *create_node(int data) {
    struct node *new_node = malloc(sizeof(struct node));
    new_node->next = NULL;
    new_node->data = data;
    return new_node;
}

// Inserts at the head of a linked list
// Returns a pointer to the new head of the list
struct node *insert_at_head(struct node *head, int data) {
    struct node *new_node = create_node(data);
    new_node->next = head;
    return new_node;
}

// Prints a linked list
void print_list(struct node *head) {
    struct node *curr = head;
    while (curr != NULL) {
        printf("%d -> ", curr->data);
        curr = curr->next;
    }
    printf("X\n");
}


struct node *delete_negatives(struct node *head) {


    if (head == NULL) {
        return NULL;
    }

    if (head->next == NULL && head->data > 0) {
        return NULL;
    }
    
    struct node *delete = NULL;

    if (head->next == NULL && head->data < 0) {
        delete = head;
        head = NULL;
        free(delete);

        return head;
    }

    struct node *current = head;
    struct node *prev = NULL;

    while (current != NULL) {

        if (current->data < 0) {
            delete = current;

            if (prev != NULL) {
                prev->next = current->next;
            }
            current = current->next;
            free(delete);
        }
        else {
            prev = current;
            current = current->next;
        }
    }

    return head;
}

Editor is loading...
Leave a Comment