Advertisement
jbn6972

Untitled

Sep 19th, 2022
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.60 KB | None | 0 0
  1. // Code Written by : John Nixon
  2. // Date: 19:09:2022  Time: 19:28:45
  3. // Copyrights are applicable
  4. #include <bits/stdc++.h>
  5. using namespace std;
  6. #define ll long long
  7. #define vi vector<int>
  8. #define vll vector<long long int>
  9.  
  10. struct Node{
  11.     int data;
  12.     Node *link;
  13. };
  14.  
  15. Node* getNewNode(int data){
  16.     Node* node = new Node;
  17.     node->data = data;
  18.     node->link = NULL;
  19.     return node;
  20. }
  21.  
  22. void insertNode(Node **head,int data){
  23.     Node *newNode = getNewNode(data);
  24.     Node* ptr;
  25.     if(*head == NULL){
  26.         *head = newNode;
  27.     }
  28.  
  29.     else{
  30.         ptr = *head;
  31.  
  32.         while(ptr->link != NULL){
  33.             ptr = ptr->link;
  34.         }
  35.         ptr->link = newNode;
  36.     }
  37. }
  38.  
  39. Node* createLinkedList(int arr[],int n){
  40.     Node *head = NULL;
  41.     for (int i = 0;i<n;i++){
  42.         insertNode(&head,arr[i]);
  43.     }
  44.     return head;
  45. }
  46.  
  47. void printLinkedList(Node *head){
  48.     while(head != NULL){
  49.         cout<<head->data<<"->";
  50.         head = head->link;
  51.     }
  52.     cout<<"NULL";
  53. }
  54.  
  55.  
  56. void printReverse(Node *head){
  57.     if(head == NULL){
  58.         return;
  59.     }
  60.     else{
  61.         printReverse(head->link);
  62.         cout<<head->data<<"->";
  63.     }
  64. }
  65.  
  66. int main()
  67. {
  68. #ifndef ONLINE_JUDGE
  69.     freopen("input.txt", "r", stdin);
  70.     freopen("output.txt", "w", stdout);
  71. #endif
  72.     std::ios::sync_with_stdio(false);
  73.  
  74.     int n =10;
  75.     int num;
  76.     int arr[n];
  77.  
  78.     for (int i = 0;i<n;i++){
  79.         cin>>num;
  80.         arr[i] = num;
  81.     }
  82.    
  83.     Node *head =  createLinkedList(arr,n);
  84.     printLinkedList(head);
  85.     cout<<endl;
  86.     printReverse(head);
  87.     cout<<endl;
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement