How to reverse a singly linked list in C

2 Answers

0 votes
#include <stdio.h>

typedef struct Node {
    char ch;
    struct Node* next;
} Node;

void print_list(Node* root) {
    while (root) {
        printf("%c ", root->ch);
        root = root->next;
    }
    
    printf("\n");
}

Node* reverse_list(Node* root) {
    Node* new_root = NULL;
    
    while (root) {
        Node* next = root->next;
        root->next = new_root;
        new_root = root;
        root = next;
    }
    
    return new_root;
}

int main() {
    Node e = { 'e', NULL };
    Node d = { 'd', &e };
    Node c = { 'c', &d };
    Node b = { 'b', &c };
    Node a = { 'a', &b };

    Node* root = &a;
    
    print_list(root);
    
    root = reverse_list(root);
    
    print_list(root);

    return 0;
}


 
/*
run:
 
a b c d e 
e d c b a 
 
*/ 
   
 

 



answered Jun 13, 2024 by avibootz
0 votes
#include <stdio.h>

typedef struct Node {
    char ch;
    struct Node* next;
} Node;

void print_list(Node* root) {
    while (root) {
        printf("%c ", root->ch);
        root = root->next;
    }
    
    printf("\n");
}

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;
}

int main() {
    Node e = { 'e', NULL };
    Node d = { 'd', &e };
    Node c = { 'c', &d };
    Node b = { 'b', &c };
    Node a = { 'a', &b };

    Node* root = &a;
    
    print_list(root);
    
    reverse_list(&root);
    
    print_list(root);

    return 0;
}


 
/*
run:
 
a b c d e 
e d c b a 
 
*/ 
   
 

 



answered Jun 13, 2024 by avibootz
...