Double-chained Circular List in C / C ++

1

I'm having trouble removing the first and last elements of this circular list.

// Created by Thiago Cunha on 25/05/2017.
//

#include "double_linked_list_circular.h"

int count = 0;

List* init() {
    return NULL;
}

List* insertInit(List* list, int data) {

    List* temp = (List *) malloc (sizeof(List));
    temp->data = data;

    if (isEmpty(list)) {
        temp->previous = temp;
        temp->next = temp;
        return temp;
    }

    temp->next = list;
    temp->previous = list->previous;
    list->previous->next = temp;
    list->previous = temp;
    list = temp;

    return list;

}

List* insertFinish(List* list, int data) {

    List* temp = (List *) malloc (sizeof(List));
    temp->data = data;


    if (isEmpty(list)) {
        temp->previous = temp;
        temp->next = temp;
        return temp;
    }

    temp->next = list;
    list->previous->next = temp;
    temp->previous = list->next;
    list->previous = temp;

    return list;

}

void displayInit(List* list) {
    cout << "Display Init: " << list->data << endl;
}

void displayFinish(List* list) {
    cout << "Display finish: " << list->previous->data << endl;

}

void display(List* list) {

    if (isEmpty(list)) {
        cout << "Your list is empty." << endl;
        return;
    }

    List* p = list;
    cout << "[ ";
    do {
        cout << p->data << " ";
        p = p->next;
    } while (p != list);
    cout << " ]" << endl << endl;

}

List* removeInit(List* list) {




}

List* removeFinish(List* list) {



}


bool isEmpty(List* list) {
    return list == NULL;
}

int size() {
    return count;
}

void toIncrease() {
    ++count;
}

void toDesincrease() {
    --count;
}
    
asked by anonymous 30.05.2017 / 15:24

1 answer

1

I was able to solve the problem of removing the last element.

List* removeFinish(List* list) {

if (isEmpty(list)) {
    return NULL;
}

if ( (list->previous == list) && (list->next == list) ) {
    free(list);
    return NULL;
}

List* p = list->previous;
p->previous->next = list;
list->previous = p->previous;

free(p);

cout << "Data was removed with successfully!" << endl;

return list;
}

To access the entire code, come with me on this link and be sure to book your star on Github!

    
23.10.2017 / 17:31