vendredi 23 août 2019

Returning from a function using `return` inside an `if` statement

I have coded a program to insert a node anywhere the user wants. So my question is whenever we want to return from a method, we can use return to come out of it, provided some condition.

Here is the code:

#include<bits/stdc++.h>
using namespace std;
struct node{
    int data;
    node* next;
};
node* head = NULL; 
node* temp;
void insertAnywhere(int x, int& pos){
    static int size = 0;
    size++;
    temp = new node();
    if(size < pos){ 
        cout<<"linkedlist size less than pos at which the node is gonna enter"; 
        return;
    }
    else{
        temp -> data = x;
        if (pos == 1){
          temp -> next = head;
          head = temp;
          return;
      }
       node* temp1 = head;
       for(int i = 0; i < pos-2; i++){
          temp1 = temp1 -> next;
       }
       temp -> next = temp1 -> next;
       temp1 -> next = temp;
    }
}
void print(){
    node* iterator = head;
    while(iterator != NULL){
        cout<< iterator -> data;
        iterator = iterator -> next;
        cout<< " ";
    }
    cout<<"\n"; 
}
int main(){
    int x, pos;
    char ch;
    for(int i = 0; i < 4; i++){
        cout<<"enter the value and the pos the node is to be inserted \n";
        cin>>x>>pos;
        insertAnywhere(x, pos);
        print();
    }
    return 0;
}

So right there inside the else statement, I have used a return that should take me outta method whenever the pos is not 1, but it ain't doing that and I am unable to find out the problem residing in the code. For example: When I want to insert a node at the second position, the return must take me out of the method, but it isn't. Any help would be appreciable :)

Aucun commentaire:

Enregistrer un commentaire