C Program to Reverse a Singly Linked List






Reverse a Singly Linked List in C


Program to Reverse a Singly Linked List in C

This program demonstrates how to reverse a singly linked list in C. The reversal is achieved by iteratively changing the direction of the pointers in the list.

Program Structure

The program consists of the following components:

  • struct Node: Defines the structure of a node in the singly linked list.
  • insert function: Adds a new node to the front of the list.
  • printList function: Prints the elements of the list.
  • reverseList function: Reverses the singly linked list.
  • main function: Demonstrates the use of these functions.

Program Code


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

// Definition of the singly linked list node structure
struct Node {
    int data;          // Data stored in the node
    struct Node* next; // Pointer to the next node
};

// Function to insert a new node at the front of the list
void insert(struct Node** head_ref, int new_data) {
    // Allocate memory for the new node
    struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
    // Assign data to the new node
    new_node->data = new_data;
    // Link the new node to the current head
    new_node->next = *head_ref;
    // Update the head to point to the new node
    *head_ref = new_node;
}

// Function to print the linked list
void printList(struct Node* node) {
    // Traverse the list and print each node's data
    while (node != NULL) {
        printf("%d -> ", node->data);
        node = node->next;
    }
    printf("NULL\n");
}

// Function to reverse the linked list
void reverseList(struct Node** head_ref) {
    struct Node* prev = NULL;  // Initialize previous node to NULL
    struct Node* current = *head_ref;  // Start with the head node
    struct Node* next = NULL;  // Initialize next node to NULL
    
    // Traverse the list and reverse the links
    while (current != NULL) {
        next = current->next;  // Store the next node
        current->next = prev;  // Reverse the current node's pointer
        prev = current;  // Move the previous pointer forward
        current = next;  // Move the current pointer forward
    }
    // Update the head to the last node, which is now the first node
    *head_ref = prev;
}

// Main function to demonstrate the reversal
int main() {
    struct Node* head = NULL;

    // Insert elements into the list
    insert(&head, 5);
    insert(&head, 10);
    insert(&head, 15);
    insert(&head, 20);

    // Print the original list
    printf("Original List: \n");
    printList(head);

    // Reverse the linked list
    reverseList(&head);

    // Print the reversed list
    printf("Reversed List: \n");
    printList(head);

    return 0;
}
    

Explanation

The program starts by defining a Node structure, which consists of an integer data field and a pointer to the next node. The insert function is used to add new nodes at the beginning of the list, updating the head pointer accordingly.

The printList function traverses the linked list from the head to the end, printing each node’s data. The reverseList function is where the reversal logic takes place. It iterates through the list, adjusting the pointers to reverse the direction of the list. Finally, the main function demonstrates the process by creating a list, printing it, reversing it, and then printing the reversed list.

Output

When the program is run, the output will be:


Original List: 
20 -> 15 -> 10 -> 5 -> NULL
Reversed List: 
5 -> 10 -> 15 -> 20 -> NULL
    


36 Replies to “C Program to Reverse a Singly Linked List”

  1. Singapore pools musim ini sebagai formal dalam undian lewat live balui sgp pools.

    Tentu belaka togelamia tidak dapat lagi menoleh result live sgp terbaru yaum ini langsung per letak formal sgp pools.
    Pemain Toto SGP tentu sendiri tidak dapat terkena lokasi penyedia produk rakitan nan genderang nekara.
    Maka berawal itulah karakter live ponten sgp sangatlah besar bagi gayang-gayang anggota kelas dua singapore pools.

    Oleh sebab itulah admin sekala memesankan member live balui sgp pools mudah-mudahan berkelanjutan berawas-awas.

    Di karnakan dalam singapore pools mempunyai surat sah atas adat (WLA) alias World Lottery Associalition. Data ini berdaya guna bak dokumen formal produk undian togel singapore nan dapat digunakan kontestan selama memahami
    sisi mainan ala lebih logis. Untuk mengeluarkan kapital sangatlah mudah bagi palas-palas bettor, akibat akibat itu palas-palas pelaku
    patut mengangkat pada jelih lokasi nan terpercaya beserta cepat rakitan pengeluaran result sgp.

    Pemain kadang-kadang kali memanfaatkan komposit sejak garizah lalu kajian evidensi
    akan mengangkat biji nan atas dipertaruhkan.

  2. I’m truly enjoying the design and layout of your website.
    It’s a very easy on the eyes which makes it much more pleasant
    for me to come here and visit more often. Did you hire out a designer to create your theme?
    Exceptional work!

  3. Hello very nice blog!! Man .. Beautiful .. Superb ..
    I will bookmark your website and take the feeds additionally?

    I’m glad to search out so many helpful info here within the publish,
    we need work out more strategies in this regard, thank you for sharing.
    . . . . .

  4. GT mods are really interesting because they add new features.

    Many players use mods to try new features, especially in allowed modes.

    A number of mods change movement mechanics, while others focus on visuals.

    There are also utility mods that add helpful tools.

    Popular mod menus are widely recognized because they bundle multiple features into
    one interface.
    Different menus offer different features, so players usually choose based on preference.

    It’s important to use mods responsibly, and only in private
    rooms.
    Misusing mods can create problems for other players.

    The GT modding scene is constantly evolving, with new features being updated frequently.

    Community modders work on improvements to fix bugs.

    With each new game update, some mods break, so staying informed
    is useful.
    All things considered, mods add variety for experienced players, when used responsibly.

  5. Greetings, I do think your web site could possibly be having internet browser compatibility problems.
    Whenever I lokk at your site in Safari, it looks fine however when opening in I.E.,
    it’s got some overlapping issues. I juhst wanted to give yoou a quick heads up!
    Other than that, fantastic blog!

    Feel free to surf to my webpage :: egzama neden olur

  6. Gorilla Tag mods are very popular because they add new features.

    A lot of the community uses mods to try new features, especially in allowed modes.

    A number of mods change movement mechanics, while others focus on visuals.

    Utility-based mods exist that add helpful tools.

    Well-known mod menus are commonly used because they
    combine different mods into one interface.
    Each menu is different, so players usually choose based on preference.

    Mods should be used carefully, and only in permitted environments.

    Using mods in public lobbies can lead to bans.

    The Gorilla Tag mod community is active, with updated tools being released regularly.

    Independent developers maintain their projects to keep them compatible.

    As the game updates, mods may require fixes, so checking update
    notes is useful.
    Overall, mods increase replayability for the community, when used responsibly.

  7. It is the best time to make some plans for the future and it is time to be
    happy. I’ve read this post and if I could I wish to suggest you some interesting things or advice.
    Perhaps you can write next articles referring to this article.

    I wish to read even more things about it!

  8. Hі thеre! Quick question that’s totally off topic. Do you
    knoѡ how to make your site mobile friendly? My site looks weird when viewing from my iphone4.
    I’m trying to find a theme or plugin thɑt might be able to correct this problem.

    If you have any suggeѕtions, pleasee share.
    Appreciatе it!

  9. I really like your blog.. very nice colors & theme.
    Did you create this website yourself or did you
    hire someone to do it for you? Plz respond as
    I’m looking to create my own blog and would like to
    find out where u got this from. kudos

  10. Generally I do not read article on blogs, however I wish to say that this write-up very pressured me to take a look at and do
    it! Your writing taste has been amazed me. Thank you, quite
    nice article.

  11. I know this if off topic but I’m looking into starting my own weblog and was curious
    what all is required to get setup? I’m assuming having a
    blog like yours would cost a pretty penny? I’m not very internet savvy so I’m not
    100% positive. Any recommendations or advice would be greatly appreciated.
    Thank you

  12. It’s the best time to make some plans for the future and it’s time
    to be happy. I’ve learn this submit and if I could I want
    to recommend you some fascinating things or suggestions.

    Perhaps you could write subsequent articles regarding this article.
    I want to learn even more things about it!

  13. Thanks on your marvelous posting! I quite enjoyed reading it, you might be a great
    author.I will remember to bookmark your blog and will come back down the road.
    I want to encourage you continue your great writing, have a
    nice day!

Leave a Reply to טלגראס כיוונים צפון Cancel reply

Your email address will not be published. Required fields are marked *