How to reverse the input | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

How to reverse the input

input contains elements of a linked list seperated by a space and terminated by -1 output reverse linked list how to do it

8th Jun 2018, 12:20 PM
Loai Salem
Loai Salem - avatar
5 Answers
+ 4
/* C++ snippet . Note I assume that you have implemented your node using structures */ struct Node { int data; struct Node* next; }; static void reverse(struct Node** head) { struct Node* prev = NULL; struct Node* current = *head; struct Node* next = NULL; while (current != NULL) { next = current->next; current->next = prev; prev = current; current = next; } *head = prev; } /*Inside main */ ... struct Node* head = NULL; ... //Push values to linked list ... reverse(&head); ... /* The idea is you set Prev to null. Set current to next and current's next to prev in loop */
8th Jun 2018, 12:32 PM
Gopal Gautam
Gopal Gautam - avatar
+ 3
in c++ there's method called reverse in #include <algorithm> just use this one line code: reverse(myData.begin(),myData.end());
8th Jun 2018, 12:25 PM
Owenizedd
Owenizedd - avatar
+ 2
Is this a challenge from dcoder??
9th Jun 2018, 12:29 PM
Shahil Ahmed
Shahil Ahmed - avatar
+ 1
thanks but without functions will be better like using loop
8th Jun 2018, 3:32 PM
Loai Salem
Loai Salem - avatar
+ 1
yes
24th Jun 2018, 3:45 PM
Loai Salem
Loai Salem - avatar