user3120283 user3120283 - 5 months ago 31
C Question

C - Swap first and last element in doubly linked list

I'm trying to swap the first and last elements of a doubly linked list. So far i have the following code, where i create a list and add some numbers to it. But the output is the same list both times.

#include <stdio.h>
#include <stdlib.h>

struct node2 {
int number;
struct node2 *next, *prev;
};

void addNodeDouble(struct node2 **head, struct node2 **tail, int num, int thesi) {
if (*head == NULL) {
struct node2 * current;
current = (struct node2 *)malloc(1 * sizeof(struct node2));
current->number = num;
current->prev = NULL;
current->next = NULL;
*head = current;
*tail = current;
} else {
if (thesi == 1) {
struct node2 *current, *temp;
current = (struct node2 *)malloc(1 * sizeof(struct node2));
current->number = num;
temp = *head;
while (temp->next != NULL)
temp = temp->next;

temp->next = current;
current->prev = *tail;
current->next = NULL;
(*tail)->next = current;
*tail = current;
} else {
struct node2 *current;
current = (struct node2 *)malloc(1 * sizeof(struct node2));
current->number = num;
current->next = *head;
(*head)->prev = current;
*head = current;
}
}
}

void ReversedisplayList(struct node2 **head, struct node2 **tail) {
struct node2 *current;
if (*head == NULL)
printf("I lista einai adeia!\n");
else {
current = *tail;
while (current != NULL) {
printf("%d ", current->number);
current = current->prev;
}
}
}

void swapElements2(struct node2 **head, struct node2 **tail) {
struct node2 *current, *temp;

temp = (*tail)->prev;
current = *tail;

temp->next = *head;
current->next = (*head)->next;
(*head)->next = NULL;
*head = current;
}

int main() {
struct node2 *head, *tail;
head = tail = NULL;

addNodeDouble(&head, &tail, 4, 1);
addNodeDouble(&head, &tail, 8, 1);
addNodeDouble(&head, &tail, 3, 0);
addNodeDouble(&head, &tail, 1, 1);
addNodeDouble(&head, &tail, 7, 0);

printf("\n\nDoubly linked list (reversed): ");
ReversedisplayList(&head, &tail);

swapElements2(&head, &tail);
printf("\nChanged list: ");
ReversedisplayList(&head, &tail);
}


I get:

Doubly linked list (reversed): 1 8 4 3 7
Changed list: 1 8 4 3 7


But I want:

Changed list: 7 8 4 3 1

Answer

To swap the first and head and tail elements you have to walk through the following procedure. First we have to get the previous node of tail and next node of head in some temporary variable and exchange head and tail's next and prev pointers.

void swapElements2(struct node2 **head, struct node2 **tail) {
    struct node2 *ttail, *thead;

    ttail = (*tail) -> prev;
    thead = (*head) -> next;

    (*head) -> next = NULL;
    (*tail) -> prev = NULL;

    (*head) -> prev = ttail;
    (*tail) -> next = thead;

    ttail -> next = (*head);
    thead -> prev = (*tail);

    (*tail)  = ttail -> next;
    (*head)  = thead -> next;
}