Write a program to Reverse a singly Linked list

 #include <stdio.h>

#include <stdlib.h>


// Define the structure for a node in the linked list

struct Node {

    int data;

    struct Node* next;

};


// Function to create a new node with given data

struct Node* createNode(int data) {

    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));

    newNode->data = data;

    newNode->next = NULL;

    return newNode;

}


// Function to insert a node at the end of the linked list

void insertAtEnd(struct Node** head, int data) {

    struct Node* newNode = createNode(data);

    if (*head == NULL) {

        *head = newNode;

        return;

    }

    struct Node* temp = *head;

    while (temp->next != NULL) {

        temp = temp->next;

    }

    temp->next = newNode;

}


// Function to print the linked list

void printList(struct Node* node) {

    while (node != NULL) {

        printf("%d -> ", node->data);

        node = node->next;

    }

    printf("NULL\n");

}


// Function to reverse the linked list

void reverseList(struct Node** head) {

    struct Node* prev = NULL;

    struct Node* current = *head;

    struct Node* next = NULL;

    while (current != NULL) {

        next = current->next; // Store next

        current->next = prev; // Reverse current node's pointer

        prev = current; // Move pointers one position ahead

        current = next;

    }

    *head = prev;

}


int main() {

    struct Node* head = NULL;


    // Inserting nodes into the linked list

    insertAtEnd(&head, 1);

    insertAtEnd(&head, 2);

    insertAtEnd(&head, 3);

    insertAtEnd(&head, 4);

    insertAtEnd(&head, 5);


    printf("Original list: ");

    printList(head);


    // Reversing the linked list

    reverseList(&head);


    printf("Reversed list: ");

    printList(head);


    return 0;

}


Comments

Popular posts from this blog

Write a c program to Create a Circular Linked list and perform Following Operations A. Insertion At Beginning B. Insertion At End C. Insertion After a particular node Insertion Before a particular node E. Insertion at specific position F. Search a particular node G. Return a particular node H. Deletion at the beginning I. Deletion at the end J. Deletion after a particular node K. Deletion before a particular node L. Delete a particular node M. Deletion at a specific position

Write a c program to check whether the created linked list is palindrome or not

Write a c program to Create a Circular single Linked list and perform Following Operations A. Insertion After a particular node B. Insertion Before a particular node C. Search a particular node D. Return a particular node E. Deletion before a particular node F. Delete a particular node