Click here to Skip to main content
15,886,704 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to get the reverse of a linked list in c programming language.
In this problem you will have to define the funciton

void reverseList(List L)

that takes a list and reverses the order of the elements.

 

If L is an empty list, the function does nothing to it.

 

if L is a singleton list, the function does nothing to it either!

 

Example:

Input:

4

1 2 3 4

 

Output:

[4 3 2 1]


What I have tried:

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


struct Node{
    long int info;
    struct Node* next;
};

void insert(struct Node** head_addr, int new_info)
{
    struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
    new_node->info = new_info;
    new_node->next = (*head_addr);
    (*head_addr) = new_node;
}

void displayLinkedList(struct Node* head)
{
    printf("[");
    struct Node* temp = head;

    while(temp != NULL)
    {
        printf("%ld ", temp->info);
        temp = temp->next;
    }
    printf("]");
}
Posted
Updated 23-May-21 20:09pm
Comments
Sandeep Mewara 24-May-21 2:02am    
You tried and that's good. You must have some confusion or seeking clarity. What is that?
CPallini 24-May-21 2:04am    
It looks to me your code already inserts the elements in reverse order, so you only need to actually process the input. What's the problem?

1 solution

Because you can only traverse a single-link linked list in one direction, what you have to do is:
1) Create a new head called reversed, set it to null.
2) Loop through the existing list processing each node in turn:
2.1) Save the Next link
2.2) Insert the node at the front of the new list, by setting it's Next pointer to the existing reversed
2.3) Set reversed to the current node.
2.4) Set the current node to the link you saved in 2.1
2.5) Exit the loop when the current node is null.
3) Set the list head to reversed
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900