# 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**

#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