In: Computer Science
C++ Question
Input:
4 -> 2 -> 1 -> NULL
Output:
4 -> 2 -> 1 -> 4 -> 2 -> 1 -> NULL
Note:- code should work on visual studio and provide screenshot of output along with code
Below is the c++ solution with output screenshot
Code :
#include <stdlib.h>
#include <iostream>
#include <vector>
using namespace std;
// Create a node
struct Node {
  int item;
  struct Node* next;
};
// function to insert element in the link list
void insert(struct Node** ref, int data) {
  struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
  struct Node* last = *ref;
  new_node->item = data;
  new_node->next = NULL;
  if (*ref == NULL) {
    *ref = new_node;
    return;
  }
  while (last->next != NULL)
    last = last->next;
  last->next = new_node;
  return;
}
// Print the linked list
void printList(struct Node* node) {
  while (node != NULL) {
    cout << node->item << " -> ";
    node = node->next;
  }
  cout<<"NULL\n";
}
int main() {
  struct Node* head = NULL;
  int n;
  string input;
  vector<int> temp;
  cout<<"Enter numbers into link list (Enter NULL to stop):\n";
  while(1){
    cin>>input;
    if(input == "NULL" || input == "null"){
        break;
    }
     n = stoi(input);
     temp.push_back(n);
     insert(&head, n);
  }
  cout << "\nInput Linked list: \n";
  printList(head);
  for(int i=0;i<temp.size();i++){
    insert(&head, temp[i]);
  }
  cout<<"\n After merging link list to itself:\n";
  printList(head);
}
Output :

Note : for better formatting please refer to the code screenshot below
