May 11, 2023

Brute Force Techniques I

This is a description
struct Node {
    int data;
    struct Node* prev;
    struct Node* next;
};

struct Node* createNode(int data) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = data;
    newNode->prev = NULL;
    newNode->next = NULL;
    return newNode;
}

void insert(struct Node** head, int data, int position) {
    if (position <= 0) {
        printf("Invalid position\n");
        return;
    }

    struct Node* newNode = createNode(data);
    struct Node* current = *head;

    if (position == 1 || current == NULL) {
        // Insert at front or if list is empty
        newNode->next = *head;
        if (*head != NULL)
            (*head)->prev = newNode;
        *head = newNode;
    } else {
        // Insert at position
        for (int i = 1; i < position - 1 && current->next != NULL; ++i)
            current = current->next;

        newNode->next = current->next;
        if (current->next != NULL)
            current->next->prev = newNode;

        current->next = newNode;
        newNode->prev = current;
    }
}

void delete(struct Node** head, int position) {
    if (*head == NULL || position <= 0) {
        printf("Invalid position\n");
        return;
    }

    struct Node* current = *head;

    if (position == 1) {
        // Delete at front
        *head = current->next;
        if (*head != NULL)
            (*head)->prev = NULL;
        free(current);
    } else {
        // Delete at position
        for (int i = 1; i < position && current != NULL; ++i)
            current = current->next;

        if (current == NULL) {
            printf("Invalid position\n");
            return;
        }

        if (current->prev != NULL)
            current->prev->next = current->next;
        else
            *head = current->next;

        if (current->next != NULL)
            current->next->prev = current->prev;

        free(current);
    }
}

void traverseList(struct Node* head) {
    printf("Doubly Linked List: ");
    while (head != NULL) {
        printf("%d ", head->data);
        head = head->next;
    }
    printf("\n");
}

void main() {
    struct Node* head = NULL;

    insert(&head, 1, 1);
    insert(&head, 2, 2);
    insert(&head, 3, 3);

    traverseList(head);

    delete(&head, 2);
    delete(&head, 1);

    traverseList(head);
}