Monday, January 18, 2021

nth node from the end

 There are 2 approaches. 1. LENGTH OF LL 2.TWO POINTER APPROACH

Note: node*& : reference to a pointer/ pointer reference

node* : simple pointer to iterate over a ll

node** : to point to the head of ll- for head manipulation

 

Node is a data type.

1.USING LENGTH OF THE LL

#include <iostream>

#include <bits/stdc++.h>

using namespace std;

//nth node from the end

class Node{

    public:

    int data;

   struct Node* next;

    };

    

//function to get the nth node from the last of Linkedlist;

void printnthfromlast(struct Node*head, int n){

    int len=0,i;

    struct Node* temp=head; //temp node points to head

    while(temp!=NULL){

        temp= temp->next;

        len++;

        

    }

  if(len<n)

  return;

  temp= head;

  for (i=1; i<len-n+1; i++)

  temp= temp->next;

  cout<<temp->data;

  return;

    

}


void push(struct Node** head_ref, int new_data){

   struct Node* new_node= new Node();

   new_node->data= new_data;

   new_node->next= (*head_ref);

   (*head_ref)= new_node; //move the head point to new node

}





int main() {

  struct Node* head= NULL; //create an empty linkedlist

  push(&head, 20);

  push(&head, 4);

  push(&head, 15);

  push(&head, 35);

  printnthfromlast(head, 4);

return 0;

}


2.TWO POINTER APPROACH

#include <iostream>
using namespace std;
#include <bits/stdc++.h>
//2POINTER APPROACH

struct Node{
    int data;
     struct Node* next;
    };
    
//function to get nth node from the last
void printnthfromlast(struct Node* head, int n)
{
   struct Node *main_ptr= head;
   struct Node *ref_ptr= head;
    int count=0;
   if(head!=NULL)
   {
       while(count<n)
       {  if(ref_ptr==NULL)
         {
           printf("%d is greater than the no of" "nodes in list", n );
           return;
         } //if ends
            ref_ptr = ref_ptr->next;
            count++;
       } //while loop ends
       
   
    
    if(ref_ptr==NULL)
    {
       head= head->next;
       if (head!= NULL) 
       
           printf("Node no. %d from last is %d", n, main_ptr->data);
           
    }//if++ ends   
       else 
       {
           while (ref_ptr!= NULL)
           {
               main_ptr= main_ptr->next;
               ref_ptr= ref_ptr->next;
           }//while ends
           printf("Node no.%d from last is %d", n, main_ptr->data);
       }//else ends
    }
}
    void push(struct Node** head_ref, int new_data)
    { struct Node* new_node= new Node();
      new_node->data= new_data;
      new_node->next= (*head_ref);
      (*head_ref)= new_node;  
        
    }
    
    
int main() {
struct Node* head= NULL;
push(&head, 20);
push(&head, 4);
push(&head, 15);
push(&head, 35);
printnthfromlast(head, 4);
return 0;
}

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home