Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- rlinked.h:
- #include <iostream>
- using namespace std;
- // Structure for Node in linked list
- struct Node {
- int value = 0; // variable for Data
- Node* next = NULL; // pointer to the next node
- };
- // Function for inserting a node to a linked list
- // in the last by recursion.
- void insertRecur(Node** head, int value);
- rlinked.cpp:
- #include <iostream>
- #include "rlinked.h"
- using namespace std;
- // Function
- // Name: insertRecur
- // Parameters:
- // Node** head - pointer to the head pointer of
- // the Linked list
- //
- //int value - data for the new node
- //
- // Return: Void
- //
- // the function will traverse the linked list
- // till the last node and create a new node with
- // the given data and sttach it at last.
- //
- void insertRecur(Node** head, int value)
- {
- // check whether the head node is created
- // if not, create a new node and attach it.
- if((*head) == NULL)
- {
- (*head) = new Node();
- (*head)->value = value;
- (*head)->next = NULL;
- return;
- }
- // check if the next node is null
- if((*head)->next == NULL)
- {
- //if it is null, create a new node.
- Node* temp = new Node();
- temp->value = value;
- // assign the value to the new node
- temp->next = NULL;
- // attaching the new node to the tail
- // of the list
- (*head)->next = temp;
- return;
- }
- else
- {
- // if the next node is not null
- // call the function recursively
- // passing the next pointer
- // and value.
- insertRecur(&((*head)->next),value);
- }
- }
- main.cpp:
- #include <iostream>
- #include "rlinked.h"
- using namespace std;
- int main()
- {
- // ls is the head node of the LinkedList
- // Initializing the head node, ls to NULL
- Node* ls = NULL;
- //Inserting values to the Linked List
- insertRecur(&ls,1);
- insertRecur(&ls,2);
- insertRecur(&ls,3);
- insertRecur(&ls,4);
- insertRecur(&ls,5);
- insertRecur(&ls,-2);
- // current is a node pointer
- // It will point to the head node, ls
- Node* current = ls;
- // current will be an alias to the head pointer, ls
- // changing the value of current will not affect the
- // head pointer
- cout<<"Linked List: "<<endl;
- // Traversing through Linked list
- // to print the Linked List
- while(current != NULL)
- {
- cout<<current->value<<" ";
- current = current->next;
- }
- cout<<endl;
- return 1;
- }
- Output:
- $ g++ rlinked.h rlinked.cpp main.cpp
- $ ./a.exe
- Linked List:
- 1 2 3 4 5 -2
Advertisement
Add Comment
Please, Sign In to add comment