Reversing Linked List in C

88 Views Asked by At

I've been working on a code to reverse a linked list, but I only seem to be getting the first element printed out in my list. Here is my function:

void reverseSqueue(Squeue squeue) {
    if (squeue -> first == NULL || squeue -> last == NULL){
        return;
    }
    Node* temp = NULL;
    Node* curr = squeue -> first;
    squeue -> first = squeue -> last;
    squeue -> last = curr;

    /*if (squeue -> first != squeue -> last){
      curr = curr -> next;
    }

    printf("%s\n", curr -> next -> value);
    printf("%s\n", curr -> value);
    printf("%s\n", curr -> prev -> value);
    printf("______________\n");
    printf("%s\n", squeue -> first -> value);
    Node* nde = squeue -> first;
    while (nde != NULL){
        printf("%s\n", nde -> value);
    nde = nde -> prev;
    }*/
    while (curr != NULL){
    /*if (curr != squeue -> first || curr != squeue -> last){
        if (curr -> next == squeue -> last){
            curr = NULL;
        }else{*/
        temp = curr;
        curr -> next = curr;
        curr = temp;
        curr = curr -> prev;
      //}
    //}else{
    //curr = NULL;
    //}
    }
}

I apologize for the messy code, I tried running multiple tests and commented them out here; I had code before that worked fine but gave a garbage value warning in OClint, so I tried fixing them and now my code just doesn't seem to work anymore. If nothing else works, I can just go back to my original code. Any input is much appreciated!

struct node {
  char *value;
  struct node *next;
  struct node *prev;
};
typedef struct node Node;

struct squeue {
   struct node* first;
   struct node* last;
};
typedef struct squeue * Squeue;
1

There are 1 best solutions below

0
On

With curr->next = curr you are saying that the next node of the current node is the current node, that is, current node points to itself as it's next node.

Node *first = squeue->last; 
squeue->last = squeue->first; // the last node is now the first
squeue->first = first; // squeue->first = original order squeue->last

Node *curr = first; 
while (curr != NULL) { // loop begins with the original order last node,
                       // but new order first node

    // curr->next, curr->prev = curr->prev, curr->next
    Node *prev = curr->prev; // saves the curr's prev
    curr->prev = curr->next; // modifies curr's prev, now pointing to curr's next
    curr->next = prev; // curr's next now points to it's original prev

    curr = curr->next; // the next curr is the original order curr's prev,
                       // but the now order curr's next
}