Search
 
SCRIPT & CODE EXAMPLE
 

CPP

Nth node from end of linked list



/* struct Node {
  int data;
  struct Node *next;
  Node(int x) {
    data = x;
    next = NULL;
  }
};
*/

//Function to find the data of nth node from the end of a linked list.
int getNthFromLast(Node *head, int n)
{
       // Your code here
    Node* current, * prev, * temp;
	current = head;
	prev = NULL;
	while (current != NULL)
	{
		temp = current->next;
		current->next = prev;
		prev = current;
		current = temp;
	}
	head = prev;
    int cnt=1;
    while(head!=NULL)
    {
        if(cnt==n&&head!=NULL)
        {
            return head->data;
        }
        cnt++;
        head=head->next;
    }
    return -1;
}
Comment

PREVIOUS NEXT
Code Example
Cpp :: Resize method in c++ for arrays 
Cpp :: c++ if in equivalent 
Cpp :: how to create a min priority queue of pair of int, int 
Cpp :: convert refference to pointer c++ 
Cpp :: cpp multidimensional vector 
Cpp :: sieve of eratosthenes algorithm in c++ 
Cpp :: less than operator overloading in c++ 
Cpp :: how to scan array in c++ 
Cpp :: c++ 
Cpp :: splice string in c++ 
Cpp :: c++ program to reverse an array 
Cpp :: log base 10 c++ 
Cpp :: C++ break and continue 
Cpp :: c++ standard library source 
Cpp :: migration meaning 
Cpp :: how to sort a string alphabetically in c++ 
Cpp :: lambda c++ 
Cpp :: how to code string to int converter c++ 
Cpp :: char size length c++ 
Cpp :: deep copy c++ 
Cpp :: sina + sinb formula 
Cpp :: inline in class in C++ 
Cpp :: memory leak in cpp 
Cpp :: integer range in c++ 
Cpp :: c preprocessor operations 
Cpp :: no template named vector in namespace std 
Cpp :: array length c++ 
Cpp :: print hello world in c++ 
Cpp :: cpp map insert 
Cpp :: vector in c++ 
ADD CONTENT
Topic
Content
Source link
Name
4+9 =