Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,690 questions

55,449 answers

573 users

How to reverse a singly linked list in-place in C

1 Answer

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

// Node structure for singly linked list
struct Node {
    int data;              // value stored in the node
    struct Node* next;     // pointer to the next node
};

// Reverse the linked list in-place
struct Node* reverseList(struct Node* head) {
    struct Node* prev = NULL;        // will become the new head
    struct Node* current = head;     // pointer to traverse the list
    struct Node* next = NULL;        // temporary pointer to store next node

    while (current != NULL) {
        next = current->next;        // save next node
        current->next = prev;        // reverse the link
        prev = current;              // move prev forward
        current = next;              // move current forward
    }

    return prev; // prev is the new head after full reversal
}

// Print the linked list
void printList(struct Node* head) {
    struct Node* temp = head;
    while (temp != NULL) {
        printf("%d", temp->data);
        if (temp->next != NULL) printf(" -> ");
        temp = temp->next;
    }
    printf("\n");
}

// Create a new node
struct Node* createNode(int value) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = value;
    newNode->next = NULL;
    
    return newNode;
}

int main() {
    // Create a sample list: 1 -> 2 -> 3 -> 4 -> 5
    struct Node* head = createNode(1);
    head->next = createNode(2);
    head->next->next = createNode(3);
    head->next->next->next = createNode(4);
    head->next->next->next->next = createNode(5);

    printf("Original list:\n");
    printList(head);

    // Reverse the list
    head = reverseList(head);

    printf("Reversed list:\n");
    printList(head);

    return 0;
}



/*
run:

Original list:
1 -> 2 -> 3 -> 4 -> 5
Reversed list:
5 -> 4 -> 3 -> 2 -> 1

*/

 



answered Jun 30 by avibootz
...