DEV Community

Adarsh
Adarsh

Posted on

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

Top comments (0)