How to reverse a linked list in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
  
typedef struct Node {
    int x;
    struct Node *next;
} Node;
 
void reverse_list(Node **root) {
    Node *prev = NULL;
    Node *current = *root;
    
    while (current != NULL) {
        Node *next = current->next;
        current->next = prev;
        prev = current;
        current = next;
    }
    
    *root = prev;
}
   
void add_node(Node **root, int value) {
    Node *new_node = malloc(sizeof(Node));
       
    if (new_node == NULL) {
        puts("malloc error");
        exit(1);
    }
       
    new_node->next = NULL;
    new_node->x = value;
       
    if (*root == NULL) {
        *root = new_node;
        return;
    }
       
    Node *current = *root;
    while (current->next != NULL) {
        current = current->next;
    }
    current->next = new_node;
}
   
void free_LinkedList(Node *root) {
    Node *next;
    while (root != NULL)  {  
        next = root->next;  
        free(root);  
        root = next;  
    }  
}
   
int main() {
    Node *root = NULL;
       
    add_node(&root, 7);
    add_node(&root, 300);
    add_node(&root, 88);
    add_node(&root, 9900);
    add_node(&root, 20);
       
    for (Node *current = root; current != NULL; current = current->next) {
        printf("%d\n", current->x);
    }
     
    reverse_list(&root);
     
    puts("\n");
    for (Node *current = root; current != NULL; current = current->next) {
        printf("%d\n", current->x);
    }
       
    free_LinkedList(root);
   
    return 0;
}
   
   
   
   
/*
run:
   
7
300
88
9900
20


20
9900
88
300
7
   
*/

 



answered Jan 2, 2021 by avibootz
...