The Wayback Machine - https://web.archive.org/web/20241008204134/https://www.geeksforgeeks.org/nth-node-from-the-end-of-a-linked-list/
Open In App

Program for Nth node from the end of a Linked List

Last Updated : 01 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a Linked List of M nodes and a number N, find the value at the Nth node from the end of the Linked List. If there is no Nth node from the end, print -1.

Examples:

Input: 1 -> 2 -> 3 -> 4, N = 3
Output: 2
Explanation: Node 2 is the third node from the end of the linked list.

Input: 35 -> 15 -> 4 -> 20, N = 4
Output: 35
Explanation: Node 35 is the fourth node from the end of the linked list.

[Naive Approach] Finding the length of list – Two Pass – O(M) Time and O(1) Space

The idea is to count the number of nodes in linked list in the first pass, say len. In the second pass, return the (len – n + 1)th nodes from beginning of the Linked List.

C++14
// C++ program to find Nth node from end of linked list

#include <bits/stdc++.h>
using namespace std;

// Link list node
struct Node {
    int data;
    Node* next;
    
      // Constructor to initialize a new node with data
    Node(int new_data) {
        data = new_data;
        next = nullptr;
    }
};

// Function to find the Nth node from the last of a linked list
int findNthFromLast(Node* head, int N) {
    int len = 0, i;
  
      // Pointer to store the copy of head
    Node* temp = head;

    // Count the number of nodes in Linked List
    while (temp != NULL) {
        temp = temp->next;
        len++;
    }

    // Check if value of N is not
    // more than length of the linked list
    if (len < N)
        return -1;

    temp = head;

    // Get the (len - N + 1)th node from the beginning
    for (i = 1; i < len - N + 1; i++)
        temp = temp->next;

    return temp->data;
}

int main() {
  
    // Create a hard-coded linked list:
    // 35 -> 15 -> 4 -> 20
    Node* head = new Node(35);
    head->next = new Node(15);
    head->next->next = new Node(4);
    head->next->next->next = new Node(20);

    // Function Call to find the 4th node from end
    cout << findNthFromLast(head, 4);
    return 0;
}
C
// C program to find Nth node from end of linked list

#include <stdio.h>

// Link list node
struct Node {
    int data;
    struct Node* next;
};

// Function to find the Nth node from the last of a linked list
int findNthFromLast(struct Node* head, int N) {
    int len = 0, i;
  
    // Pointer to store the copy of head
    struct Node* temp = head;

    // Count the number of nodes in Linked List
    while (temp != NULL) {
        temp = temp->next;
        len++;
    }

    // Check if value of N is not more than length of the linked list
    if (len < N)
        return -1;

    temp = head;

    // Get the (len - N + 1)th node from the beginning
    for (i = 1; i < len - N + 1; i++)
        temp = temp->next;

    return temp->data;
}

// Function to create a new node
struct Node* createNode(int new_data) {
    struct Node* new_node = 
       (struct Node*)malloc(sizeof(struct Node));
    new_node->data = new_data;
    new_node->next = NULL;
    return new_node;
}

int main() {
  
    // Create a hard-coded linked list:
    // 35 -> 15 -> 4 -> 20
    struct Node* head = createNode(35);
    head->next = createNode(15);
    head->next->next = createNode(4);
    head->next->next->next = createNode(20);
  
    // Function Call to find the 4th node from end
    printf("%d\n", findNthFromLast(head, 4));

    return 0;
}
Java
// Java program to find Nth node from
// end of linked list

// Link list node
class Node {
    int data;
    Node next;
    
    // Constructor to initialize a new node with data
    Node(int new_data) {
        data = new_data;
        next = null;
    }
}

public class GFG {
      // Function to find the Nth node from the last of a linked list
    static int findNthFromLast(Node head, int N) {
        int len = 0, i;
      
        // Pointer to store the copy of head
        Node temp = head;

        // Count the number of nodes in Linked List
        while (temp != null) {
            temp = temp.next;
            len++;
        }

        // Check if value of N is not more than length of the linked list
        if (len < N)
            return -1;

        temp = head;

        // Get the (len - N + 1)th node from the beginning
        for (i = 1; i < len - N + 1; i++)
            temp = temp.next;

        return temp.data;
    }

    public static void main(String[] args) {
      
        // Create a hard-coded linked list:
        // 35 -> 15 -> 4 -> 20
        Node head = new Node(35);
        head.next = new Node(15);
        head.next.next = new Node(4);
        head.next.next.next = new Node(20);

        // Function Call to find the 4th node from end
        System.out.println(findNthFromLast(head, 4));
    }
}
Python
# Python3 program to find Nth node from end of linked list

# Link list node
class Node:
  
   # Constructor to initialize a new node with data
    def __init__(self, new_data):
        self.data = new_data
        self.next = None

# Function to find the Nth node from the last of a linked list
def findNthFromLast(head, N):
    length = 0
    temp = head

    # Count the number of nodes in Linked List
    while temp is not None:
        temp = temp.next
        length += 1

    # Check if value of N is not more than length of the linked list
    if length < N:
        return -1

    temp = head

    # Get the (length - N + 1)th node from the beginning
    for _ in range(1, length - N + 1):
        temp = temp.next

    return temp.data

if __name__ == "__main__":
  
    # Create a hard-coded linked list:
    # 35 -> 15 -> 4 -> 20
    head = Node(35)
    head.next = Node(15)
    head.next.next = Node(4)
    head.next.next.next = Node(20)

    # Function Call to find the 4th node from end
    print(findNthFromLast(head, 4))
C#
// C# program to find N'th node from end of linked list
using System;

// Link list node
class Node {
    public int data;
    public Node next;
    
    // Constructor to initialize a new node with data
    public Node(int new_data) {
        data = new_data;
        next = null;
    }
}

// Function to find the Nth node from the last of a linked list
class GFG {
    static int FindNthFromLast(Node head, int N) {
        int len = 0;
        Node temp = head;

        // Count the number of nodes in Linked List
        while (temp != null) {
            temp = temp.next;
            len++;
        }

        // Check if value of N is not more than length of the linked list
        if (len < N)
            return -1;

        temp = head;

        // Get the (len - N + 1)th node from the beginning
        for (int i = 1; i < len - N + 1; i++)
            temp = temp.next;

        return temp.data;
    }

    static void Main() {
      
        // Create a hard-coded linked list:
        // 35 -> 15 -> 4 -> 20
        Node head = new Node(35);
        head.next = new Node(15);
        head.next.next = new Node(4);
        head.next.next.next = new Node(20);

        // Function Call to find the 4th node from end
        Console.WriteLine(FindNthFromLast(head, 4));
    }
}
JavaScript
// Javascript program to find N'th node from end of linked list

// Link list node
class Node {
    
    // Constructor to initialize a new node with data
    constructor(new_data) {
        this.data = new_data;
        this.next = null;
    }
}

// Function to find the Nth node from the last of a linked list
function findNthFromLast(head, N) {
    let len = 0;
    let temp = head;

    // Count the number of nodes in Linked List
    while (temp !== null) {
        temp = temp.next;
        len++;
    }

    // Check if value of N is not more than length of the linked list
    if (len < N) {
        return -1;
    }

    temp = head;

    // Get the (len - N + 1)th node from the beginning
    for (let i = 1; i < len - N + 1; i++) {
        temp = temp.next;
    }

    return temp.data;
}

// Create a hard-coded linked list:
// 35 -> 15 -> 4 -> 20
let head = new Node(35);
head.next = new Node(15);
head.next.next = new Node(4);
head.next.next.next = new Node(20);

// Function Call to find the 4th node from end
console.log(findNthFromLast(head, 4));

Output
35

Time complexity: O(M) where M is the size of the linked list
Auxiliary Space: O(1)

[Expected Approach] Using Two Pointers – One Pass – O(M) Time and O(1) Space

The idea is to maintain two pointers, say main_ptr and ref_ptr point to the head of Linked List and move ref_ptr to the Nth node from the head to ensure that the distance between main_ptr and ref_ptr is (N – 1). Now, move both the pointers simultaneously until ref_ptr reaches the last node. Since the distance between main_ptr and ref_ptr is (N – 1), so when ref_ptr will reach the last node, main_ptr will reach Nth node from the end of Linked List. Return the value of node pointed by main_ptr.

Below image is a dry run of the above approach:


Follow the given steps to solve the problem:

  • Maintain two pointers main_ptr and ref_ptr
  • Move ref_ptr to the Nth node from the start
  • Now move both main_ptr and ref_ptr, until the ref_ptr reaches the last node
  • Now return the data of the main_ptr, as it is at the Nth node from the end
C++
// C++ program to find Nth node from end of linked list

#include <bits/stdc++.h>
using namespace std;

// Link list node
struct Node {
    int data;
    Node* next;

    // Constructor to initialize a new node with data
    Node(int new_data) {
        data = new_data;
        next = nullptr;
    }
};

// function to find Nth node from the end of linked list
int nthFromEnd(Node *head, int N) {
  
    // create two pointers main_ptr and ref_ptr
    // initially pointing to head.
    Node* main_ptr = head;
    Node* ref_ptr = head;

    // move ref_ptr to the n-th node from beginning.
    for (int i = 1; i < N; i++) {
        ref_ptr = ref_ptr->next;
          
          // If the ref_ptr reaches NULL, then it means 
          // N > length of linked list
        if (ref_ptr == NULL) {
            return -1;
        }
    }

    // move ref_ptr and main_ptr by one node until
    // ref_ptr reaches last node of the list.
    while (ref_ptr->next != NULL) {
        ref_ptr = ref_ptr->next;
        main_ptr = main_ptr->next;
    }

    return main_ptr->data;
}

int main() {

    // Create a hard-coded linked list:
    // 35 -> 15 -> 4 -> 20
    Node* head = new Node(35);
    head->next = new Node(15);
    head->next->next = new Node(4);
    head->next->next->next = new Node(20);

    // Function Call to find the 4th node from end
    cout << nthFromEnd(head, 4);
    return 0;
}
C
// C program to find Nth node from end of linked list

#include <stdio.h>

// Link list node
struct Node {
    int data;
    struct Node* next;
};

// Function to find the Nth node from the last of a linked
// list
int findNthFromLast(struct Node* head, int N) {

    // Create two pointers main_ptr and ref_ptr initially
    // pointing to head
    struct Node* main_ptr = head;
    struct Node* ref_ptr = head;

    // Move ref_ptr to the N-th node from the beginning
    for (int i = 1; i < N; i++) {
        ref_ptr = ref_ptr->next;

        // If the ref_ptr reaches NULL, then it means
        // N > length of linked list
        if (ref_ptr == NULL) {
            return -1;
        }
    }

    // Move ref_ptr and main_ptr by one node until ref_ptr
    // reaches the last node of the list
    while (ref_ptr->next != NULL) {
        ref_ptr = ref_ptr->next;
        main_ptr = main_ptr->next;
    }

    return main_ptr->data;
}

// Function to create a new node
struct Node* createNode(int new_data) {
    struct Node* new_node
        = (struct Node*)malloc(sizeof(struct Node));
    new_node->data = new_data;
    new_node->next = NULL;
    return new_node;
}

int main() {

    // Create a hard-coded linked list:
    // 35 -> 15 -> 4 -> 20
    struct Node* head = createNode(35);
    head->next = createNode(15);
    head->next->next = createNode(4);
    head->next->next->next = createNode(20);

    // Function Call to find the 4th node from end
    printf("%d\n", findNthFromLast(head, 4));

    return 0;
}
Java
// Java program to find Nth node from end of linked list

// Link list node
class Node {
    int data;
    Node next;

    // Constructor to initialize a new node with data
    Node(int new_data) {
        data = new_data;
        next = null;
    }
}

public class GFG {

    // Function to find Nth node from the end of linked list
    static int nthFromEnd(Node head, int N) {
      
        // Create two pointers main_ptr and ref_ptr
        // initially pointing to head.
        Node main_ptr = head;
        Node ref_ptr = head;

        // Move ref_ptr to the N-th node from beginning.
        for (int i = 1; i < N; i++) {
            ref_ptr = ref_ptr.next;

            // If the ref_ptr reaches NULL, then it means 
            // N > length of linked list
            if (ref_ptr == null) {
                return -1;
            }
        }

        // Move ref_ptr and main_ptr by one node until
        // ref_ptr reaches last node of the list.
        while (ref_ptr.next != null) {
            ref_ptr = ref_ptr.next;
            main_ptr = main_ptr.next;
        }

        return main_ptr.data;
    }

    public static void main(String[] args) {
      
        // Create a hard-coded linked list:
        // 35 -> 15 -> 4 -> 20
        Node head = new Node(35);
        head.next = new Node(15);
        head.next.next = new Node(4);
        head.next.next.next = new Node(20);

        // Function Call to find the 4th node from end
        System.out.println(nthFromEnd(head, 4));
    }
}
Python
# Python3 program to find Nth node from end of linked list

# Link list node
class Node:
  
      # Constructor to initialize a new node with data
    def __init__(self, new_data):
        self.data = new_data
        self.next = None

# Function to find Nth node from the end of linked list
def nth_from_end(head, N):

    # Create two pointers main_ptr and ref_ptr 
    # initially pointing to head.
    main_ptr = head
    ref_ptr = head

    # Move ref_ptr to the N-th node from beginning.
    for _ in range(1, N):
        ref_ptr = ref_ptr.next

        # If the ref_ptr reaches None, then it means
        # N > length of linked list
        if ref_ptr is None:
            return -1

    # Move ref_ptr and main_ptr by one node until
    # ref_ptr reaches last node of the list.
    while ref_ptr.next is not None:
        ref_ptr = ref_ptr.next
        main_ptr = main_ptr.next

    return main_ptr.data

if __name__ == "__main__":
      
    # Create a hard-coded linked list:
    # 35 -> 15 -> 4 -> 20
    head = Node(35)
    head.next = Node(15)
    head.next.next = Node(4)
    head.next.next.next = Node(20)

    # Function Call to find the 4th node from end
    print(nth_from_end(head, 4))
C#
// C# program to find Nth node from end of linked list
using System;

class GFG {

    // Node class for the linked list
    class Node {
        public int Data;
        public Node Next;

          // Constructor to initialize a new node with data
        public Node(int newData) {
            Data = newData;
            Next = null;
        }
    }

    // Function to find the Nth node from the end of the
    // linked list
    static int NthFromEnd(Node head, int N) {
        Node mainPtr = head;
        Node refPtr = head;

        // Move refPtr to the N-th node from the beginning
        for (int i = 1; i < N; i++) {
            refPtr = refPtr ?.Next;

            // If the refPtr reaches null, then N > length
            // of linked list
            if (refPtr == null) {
                return -1;
            }
        }

        // Move refPtr and mainPtr by one node until refPtr
        // reaches the last node
        while (refPtr?.Next != null) {
            refPtr = refPtr.Next;
            mainPtr = mainPtr.Next;
        }

        return mainPtr.Data;
    }

    static void Main() {
          
        // Create a hard-coded linked list:
        // 35 -> 15 -> 4 -> 20
        Node head = new Node(35);
        head.Next = new Node(15);
        head.Next.Next = new Node(4);
        head.Next.Next.Next = new Node(20);

        // Function call to find the 4th node from the end
        Console.WriteLine(NthFromEnd(head, 4));
    }
}
JavaScript
// javascript program to find n'th
// node from end of linked list

// Linked List Node
class Node {
    
    // Constructor to initialize a new node with data
    constructor(data) {
        this.data = data;
        this.next = null;
    }
}

// Function to find Nth node from the end of linked list
function nthFromEnd(head, N) {
    let mainPtr = head;
    let refPtr = head;

    // Move refPtr to the N-th node from the beginning
    for (let i = 1; i < N; i++) {
        refPtr = refPtr.next;
        
        if (refPtr === null) {
        
            // If N is greater than the length of the linked list
            return -1;
        }
    }

    // Move refPtr and mainPtr by one node until refPtr reaches the last node
    while (refPtr.next !== null) {
        refPtr = refPtr.next;
        mainPtr = mainPtr.next;
    }

    return mainPtr.data;
}

// Create a hard-coded linked list:
// 35 -> 15 -> 4 -> 20
const head = new Node(35);
head.next = new Node(15);
head.next.next = new Node(4);
head.next.next.next = new Node(20);

// Function call to find the 4th node from end
console.log(nthFromEnd(head, 4));

Output
Node no. 4 from end is: 35

Time Complexity: O(M) where M is the length of the linked list
Auxiliary Space: O(1)



Previous Article
Next Article

Similar Reads

Cpp14 Program For Printing Nth Node From The End Of A Linked List (Duplicate)
Given a Linked List and a number n, write a function that returns the value at the n'th node from the end of the Linked List.For example, if the input is below list and n = 3, then output is "B" Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Method 1 (Use length of linked list) 1) Calculate the length of Linked
5 min read
Recursive Approach to find nth node from the end in the linked list
Find the nth node from the end in the given linked list using a recursive approach. Examples: Input : list: 4->2->1->5->3 n = 2 Output : 5 Algorithm: findNthFromLast(head, n, count, nth_last) if head == NULL then return findNthFromLast(head->next, n, count, nth_last) count = count + 1 if count == n then nth_last = head findNthFromLas
8 min read
XOR Linked List - Find Nth Node from the end
Given a XOR linked list and an integer N, the task is to print the Nth node from the end of the given XOR linked list. Examples: Input: 4 –> 6 –> 7 –> 3, N = 1 Output: 3 Explanation: 1st node from the end is 3.Input: 5 –> 8 –> 9, N = 4 Output: Wrong Input Explanation: The given Xor Linked List contains only 3 nodes. Approach: Follow
15+ min read
Delete Nth node from the end of the given linked list
Given a linked list and an integer N, the task is to delete the Nth node from the end of the given linked list. Examples: Input: 2 -> 3 -> 1 -> 7 -> NULL, N = 1 Output: The created linked list is: 2 3 1 7 The linked list after deletion is: 2 3 1 Input: 1 -> 2 -> 3 -> 4 -> NULL, N = 4 Output: The created linked list is: 1 2 3
13 min read
Remove Nth node from end of the Linked List
Given a linked list. The task is to remove the Nth node from the end of the linked list. Examples: Input : LinkedList = 1 ->2 ->3 ->4 ->5 , N = 2Output : 1 ->2 ->3 ->5Explanation: Linked list after deleting the 2nd node from last which is 4, is 1 ->2 ->3 ->5 Input : LinkedList = 7 ->8 ->4 ->3 ->2 , N = 1 Ou
15+ min read
Javascript Program For Swapping Kth Node From Beginning With Kth Node From End In A Linked List
Given a singly linked list, swap kth node from beginning with kth node from end. Swapping of data is not allowed, only pointers should be changed. This requirement may be logical in many situations where the linked list data part is huge (For example student details line Name, RollNo, Address, ..etc). The pointers are always fixed (4 bytes for most
5 min read
Swap Kth node from beginning with Kth node from end in a Doubly Linked List
Prerequisites: Doubly Linked List Given a doubly-linked list, the task is to swap Kth node from the beginning with Kth node from the ending.Note: Please note here the nodes are swapped and not the data in the nodes. Examples: Input: DLL = 1 <-> 2 <-> 3 <-> 4 <-> 5 <-> 6, K = 3 Output: 1 2 4 3 5 6 Explanation: Third nod
15+ min read
Swap Kth node from beginning with Kth node from end in a Linked List
Given a singly linked list, swap kth node from beginning with kth node from end. Swapping of data is not allowed, only pointers should be changed. This requirement may be logical in many situations where the linked list data part is huge (For example student details like Name, RollNo, Address, ..etc). The pointers are always fixed (4 bytes for most
15+ min read
Javascript Program For Writing A Function To Get Nth Node In A Linked List
Write a GetNth() function that takes a linked list and an integer index and returns the data value stored in the node at that index position. Example: Input: 1 -> 10 -> 30 -> 14, index = 2Output: 30 Explanation: The node at index 2 is 30Recommended: Please solve it on "PRACTICE" first, before moving on to the solution.Method 1 - Using Loop
4 min read
Write a function to get Nth node in a Linked List
Given a LinkedList and an index (1-based). The task is to find the data value stored in the node at that kth position. If no such node exists whose index is k then return -1. Example:  Input: 1->10->30->14, index = 2Output: 10Explanation: The node value at index 2 is 10 Input: 1->32->12->10->30->14->100, index = 8Output:
11 min read
Move the Kth Prime Number Node to the End of the Linked List
Given a singly linked list, the task is to move the Kth prime number node to the end of the list while preserving the order of other nodes. Examples: Input: 4 -> 7 -> 11 -> 3 -> 14 -> 2 -> NULL, K = 2Output: 4 -> 7 -> 3 -> 14 -> 2 -> 11 -> NULLExplanation: In the given list, the prime number nodes are 7, 11, 3, a
13 min read
Move the Kth Largest Fibonacci Number Node to the End of a Singly Linked List
Given a singly linked list containing integer values. The task is to find the Kth largest Fibonacci number within this list and move it to the end of the list. Examples: Input: 12 -> 11 -> 0 -> 5 -> 8 -> 13 -> 17 -> 21 -> NULL, K = 3Output: 12 -> 11 -> 0 -> 5 -> 13 -> 17 -> 21 -> 8 -> NULLExplanation:
12 min read
Insert Node at the End of a Linked List
Given a linked list, the task is to insert a new node at the end of the linked list. Examples: Input: LinkedList = 2 -> 3 -> 4 -> 5, NewNode = 1Output: LinkedList = 2 -> 3 -> 4 -> 5 -> 1 Input: LinkedList = NULL, NewNode = 1Output: LinkedList = 1 Approach:  Inserting at the end involves traversing the entire list until we reach
9 min read
Deletion at end (Removal of last node) in a Linked List
Given a linked list, the task is to delete the last node of the given linked list. Examples:   Input: 1 -> 2 -> 3 -> 4 -> 5 -> NULLOutput: 1 -> 2 -> 3 -> 4 -> NULL Explanation: The last node of the linked list is 5, so 5 is deleted. Input: 3 -> 12 -> 15-> NULLOutput: 3 -> 12 -> NULL Explanation: The last no
8 min read
Insert a Node at the end of Doubly Linked List
Given a Doubly Linked List, the task is to insert a new node at the end of the linked list. Examples: Input: Linked List = 1 <-> 2 <-> 3, NewNode = 4Output: Linked List = 1 <-> 2 <-> 3 <-> 4 Input: Linked List = NULL, NewNode = 1Output: Linked List = 1 Approach: Inserting at the end involves traversing the entire list
9 min read
Deletion at end (Removal of last node) in a Doubly Linked List
Given a doubly linked list, the task is to delete the last node of the given linked list. Examples: Input: 1 <-> 2 <-> 3 <-> NULLOutput: 1 <-> 2 <-> NULLExplanation: The last node of the linked list is 3, so 3 is deleted. Input: 15 -> NULLOutput: NULLExplanation: The last node of the linked list is 15, so 15 is dele
7 min read
XOR linked list- Remove first node of the linked list
Given an XOR linked list, the task is to remove the first node of the XOR linked list. Examples: Input: XLL = 4 < – > 7 < – > 9 < – > 7 Output: 7 < – > 9 < – > 7 Explanation: Removing the first node of the XOR linked list modifies XLL to 7 < – > 9 < – > 7 Input: XLL = NULL Output: List Is Empty Approach: Th
11 min read
XOR Linked List: Remove last node of the Linked List
Given an XOR linked list, the task is to delete the node at the end of the XOR Linked List. Examples: Input: 4<–>7<–>9<–>7Output: 4<–>7<–>9Explanation: Deleting a node from the end modifies the given XOR Linked List to 4<–>7<–>9 Input: 10Output: List is emptyExplanation: After deleting the only node present
15+ min read
Create new linked list from two given linked list with greater element at each node
Given two linked list of the same size, the task is to create a new linked list using those linked lists. The condition is that the greater node among both linked list will be added to the new linked list.Examples: Input: list1 = 5->2->3->8list2 = 1->7->4->5Output: New list = 5->7->4->8Input: list1 = 2->8->9->3li
8 min read
Javascript Program For Inserting A Node After The N-th Node From The End
Insert a node x after the nth node from the end in the given singly linked list. It is guaranteed that the list contains the nth node from the end. Also 1 <= n. Examples: Input : list: 1->3->4->5 n = 4, x = 2 Output : 1->2->3->4->5 4th node from the end is 1 and insertion has been done after this node. Input : list: 10->8
5 min read
Javascript Program For Moving All Occurrences Of An Element To End In A Linked List
Given a linked list and a key in it, the task is to move all occurrences of the given key to the end of the linked list, keeping the order of all other elements the same. Examples: Input : 1 -> 2 -> 2 -> 4 -> 3 key = 2 Output : 1 -> 4 -> 3 -> 2 -> 2 Input : 6 -> 6 -> 7 -> 6 -> 3 -> 10 key = 6 Output : 7 ->
6 min read
Javascript Program To Merge A Linked List Into Another Linked List At Alternate Positions
Given two linked lists, insert nodes of the second list into the first list at alternate positions of the first list. For example, if first list is 5->7->17->13->11 and second is 12->10->2->4->6, the first list should become 5->12->7->10->17->2->13->4->11->6 and second list should become empty. The
3 min read
Problems not solved at the end of Nth day
Given 3 integers K, P and N. Where, K is the number of problems given to the person every day and P is the maximum number of problems he can solve in a day. Find the total number of problems not solved after the N-th day.Examples: Input : K = 2, P = 1, N = 3 Output : 3 On each day 1 problem is left so 3*1 = 3 problems left after Nth day. Input : K
4 min read
Insert a node after the n-th node from the end
Insert a node x after the nth node from the end in the given singly linked list. It is guaranteed that the list contains the nth node from the end. Also 1 <= n. Examples: Input : list: 1->3->4->5 n = 4, x = 2 Output : 1->2->3->4->5 4th node from the end is 1 and insertion has been done after this node. Input : list: 10->8
15+ min read
Find the other end point of a line with given one end and mid
Given a midpoint of line(m1, m2) and one coordinate of a line (x1, y1), find the other end point(x2, y2) of a line. Examples: Input : x1 = –1, y1 = 2, and m1 = 3, m2 = –6 Output : x2 = 7, y2 = 10 Input : x1 = 6.4, y1 = 3 and m1 = –10.7, m2 = 4 Output : x2 = 3, y2 = 4 The Midpoint Formula: The midpoint of two points, (x1, y2) and (x2, y2) is the poi
4 min read
Why start + (end - start)/2 is preferable method for calculating middle of an array over (start + end)/2 ?
I am very sure that everyone is able to find middle index of array once you know start index and end index of array, but there are certain benefits of using start + (end - start)/2 over (start + end)/2, which are described below : The very first way of finding middle index is mid = (start + end)/2But there is a problem with this approach, what if t
8 min read
Minimize first node of Linked List by deleting first or adding one deleted node at start
Given a singly linked list, and an integer K, the task is to make the first node value as minimum as possible in K operations where in each operation: Select the first node of the linked list and remove it.Add a previously removed node at the start of the linked list. Examples: Input: list: 1->4->2->5->3, K=4 Output:1Explanation: 1st op
8 min read
Insert a Node after a given Node in Linked List
Given a linked list, the task is to insert a new node after a given node of the linked list. If the given node is not present in the linked list, print "Node not found". Examples: Input: LinkedList = 2 -> 3 -> 4 -> 5, newData = 1, key = 2Output: LinkedList = 2 -> 1 -> 3 -> 4 -> 5 Input: LinkedList = 1 -> 3 -> 5 -> 7, n
11 min read
Insert a Node after a given node in Doubly Linked List
Given a Doubly Linked List, the task is to insert a new node after a given node in the linked list. Examples: Input: Linked List = 1 <-> 2 <-> 4, newData = 3, key = 2Output: Linked List = 1 <-> 2 <-> 3 <-> 4Explanation: New node 3 is inserted after key, that is node 2. Input: Linked List = 1 <-> 2, newData = 4, k
11 min read
Insert a Node before a given node in Doubly Linked List
Given a Doubly Linked List, the task is to insert a new node before a given node in the linked list. Examples: Input: Linked List = 1 <-> 3 <-> 4, newData = 2, key = 3Output: Linked List = 1 <-> 2 <-> 3 <-> 4Explanation: New node with data 2 is inserted before the node with data = 3 Input: Linked List = 2 <-> 3,
12 min read