Write a program to find the nth node from the end of the linked list.
Example 1:
Input: 5->2->8->4->1->NULL ,n=3
Output: Nth node is 8 //return 8
Example 2:
Input: 5->2->8->4->1->NULL ,n=10
Output: Nth node is not present //return -1
Approach:
Java
public class LinkListSearchNthElement1 {public static void main(String[] args) {ListNode l = new ListNode(5);l.next = new ListNode(2);l.next.next = new ListNode(8);l.next.next.next = new ListNode(4);l.next.next.next.next = new ListNode(1);int value = 8;int length = linkedListLength(l);int nth = searchGivenNode(l, value, length);System.out.println("Nth node is " + nth);}private static int linkedListLength(ListNode node) {int length = 0;while (node != null) {node = node.next;length++;}return length;}private static int searchGivenNode(ListNode head, int value, int length) {if (length < value)return -1;int i = 0;int nth = length - value + 1;while (head != null) {i++;if (i == nth) {return head.val;}head = head.next;}return -1;}}class ListNode {int val;ListNode next;ListNode() {}ListNode(int val) {this.val = val;}ListNode(int val, ListNode next) {this.val = val;this.next = next;}}// Time Complexity : O(n)
C++
#include <bits/stdc++.h>using namespace std;//Struture of nodestruct Node{int data;Node *next;Node(int data){this->data=data;this->next=NULL;}};//function to find the nth//node from end of linked listint NthNodeFromEnd(Node *head,int n){//if linked list is empty//return -1if(head==NULL)return -1;int length=0;//node to store the head of//the linked listNode *temp=head;//iterate till end of list//and count no of nodeswhile(temp!=NULL){//increment the count//of nodeslength++;//move to the next nodetemp=temp->next;}//if no of nodes in linked//list is less than length of linked//list return -1if(length<n)return -1;else{//n from startn=length-n+1;temp=head;int count =0;while(temp!=NULL){//increment the count//the nodecount++;//if count is same as//n return the node dataif(count==n)return temp->data;//move to the next nodetemp=temp->next;}//if length is less than n return -1return -1;}}int main(){Node *head=new Node(5);head->next=new Node(2);head->next->next=new Node(8);head->next->next->next=new Node(4);head->next->next->next->next=new Node(1);int n=2;int nthNode=NthNodeFromEnd(head,n);if(nthNode==-1)cout<<"Nth node is not present\n";elsecout<<"Nth node is "<<nthNode<<"\n";return 0;}//Time Complexity: O(n)//Space Complexity:O(1)
No comments:
Post a Comment