简体   繁体   中英

How to remove last node from a linked list? - C

I'm trying to pop the last node from a doubly and circular linked list but I'm getting a headache with pointers. I've got a function that traverses the entire list til the end of it but somehow, the tmp pointer doesn't move or update. I'm traversing the entire list with a for loop instead of a while one as its more comfortable to me (and yes, ive tried with a while loop)

Here is my code:

typedef struct List {
    unsigned int size;
    Node *p_head;
    Node *p_tail;
} List;

typedef struct Node {
    void *p_value;
    struct Node *p_next;
    struct Node *p_previous;
} Node;

Bool RemoveAtEnd(List *list) {

    Node *p_node = list->p_head; /* tmp ptr */

    for (int i = 0; i < GetSize(list); ++i) {
        p_node = (p_node)->p_next;
    }
    
    /*
     * p_node var should be the last node or tail of the list shouldn't it?
     */

    printf("Tail here is %d\n", *(int *) p_node->p_value);
    list->p_tail = p_node->p_previous;
    list->p_tail->p_next = list->p_head;
    list->p_head->p_previous = list->p_tail;
    list->size--;
    DestroyNode(p_node);
    return TRUE;
}

When trying to free the node within the function valgrind says "Invalid read" when trying to traverse the list outside the function because as far i seen, the tail is pointing back to the head instead of the tail

    List *p_intList = CreateList();

    for (int i = 0; i < 5; ++i) {
        int a = i + 1;
        InsertAtEnd(p_intList, &a, sizeof(int));
    }

    RemoveAtEnd(p_intList);

    for (int i = 0; i < GetSize(p_intList); ++i) {
        printf("%d\n", *(int *) GetValueAt(p_intList, i)); // Invalid read
    }

    DestroyList(p_intList);```

in pseudocode i would do like this

you know that last-1 -> last -> head
and what you need is the list
to become like last-1 > head

  1. save the last node

    last = list.getHead()->prev;

  2. link last-1 with node head

    last-1 = list.getHead()->prev->prev;

    last-1.next = list.getHead();
    list.getHead().prev = last-1

  3. free removed node

    free(last);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM