# Write a function to reverse singly linked list

*Link lists have been favorite question asked in interview. The efficient answer by professionals makes positive response as well it is sign of good concepts. there are two method of reversing singly link list.*

**iterative**

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
#include <iostream> using namespace std; class link { private: struct node { int data; struct node *next; }*first; public: link(); virtual ~link(); void addNum(int data); void printNum(); void reverseList(); }; link::link() { first = NULL; } link::~link() { } void link::reverseList() { node *current = first; node *prev = NULL; node *next; while (current != NULL) { next = current->next; current->next = prev; prev = current; current = next; } first = prev; } void link::printNum() { node *temp; temp = first; if (temp == NULL) cout << "list is empty \n"; while (temp != NULL) { cout << temp->data; temp = temp->next; cout << "\n"; } } void link::addNum(int data) { if (first == NULL) { node *temp = new node(); temp->data = data; temp->next = NULL; first = temp; } else { node *temp; temp = first; while (temp->next != NULL) temp = temp->next; node *r = new node(); r->data = data; r->next = NULL; temp->next = r; } } int main(int argc, char** argv) { link lnode; lnode.addNum(1); lnode.addNum(2); lnode.addNum(3); lnode.addNum(4); lnode.printNum(); lnode.reverseList(); lnode.printNum(); return 0; } |

**recursion**

Recursive solution looks clean but it is always hard to think as our mind always thinks in iterative way. in c/cpp programming if a function calls itself then we name this type of **function recursive. **recursive solution needs one case where function stops calling itself, that case may be called base case.

Best example is factorial program. factorial of a number is the product of all numbers less than equal to itself, like factorial of 5 is 5*4*3*2*1.

## Leave a Reply