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;
}
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home