Linked list through recursion

adarshmaharjan

Adarsh

Posted on July 28, 2022

Linked list through recursion
#include <iostream>
using namespace std;
struct Node
{
  int data;
  struct Node *next;
};

void printList(struct Node *p)
{

  if (p == NULL)
  {
    return;
  }
  cout << p->data << " ";
  printList(p->next);
}

void recursivePrintList(struct Node *p)
{

  if (p == NULL)
  {
    return;
  }
  recursivePrintList(p->next);
  cout << p->data << " ";
}
Node *insertNode(Node *head, int data)
{
  Node *temp = new Node();
  temp->data = data;
  temp->next = head;
  head = temp;
  return head;
}
int main()
{
  Node *head = NULL;
  head = insertNode(head, 1);
  head = insertNode(head, 2);
  head = insertNode(head, 3);
  head = insertNode(head, 4);
  head = insertNode(head, 5);
  printList(head);
  cout << endl;
  recursivePrintList(head);
  cout << endl;
}
Enter fullscreen mode Exit fullscreen mode
πŸ’– πŸ’ͺ πŸ™… 🚩
adarshmaharjan
Adarsh

Posted on July 28, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related