# Delete Kth nodes from the beginning and end of a Linked List

• Difficulty Level : Expert
• Last Updated : 18 Jun, 2021

Given a singly Linked List and an integer K denoting the position of a Linked List, the task is to delete the Kth node from the beginning and end of the Linked List.

Examples:

Input: 1 â†’ 2 â†’ 3 â†’ 4 â†’ 5 â†’ 6, K = 3
Output: 1 â†’ 2 â†’ 5 â†’ 6
Explanation: Deleted Nodes : 3, 4

Input: 1 â†’ 2 â†’ 3 â†’ 4 â†’ 5 â†’ 6, K = 1
Output: 2 â†’ 3 â†’ 4 â†’ 5

Input: 1 â†’ 2 â†’ 3 â†’ 4 â†’ 5 â†’ 6, K = 4
Output: 1 â†’ 2 â†’ 5 â†’ 6

Approach: Follow the steps to solve the problem

1. Initialize two pointers fast and slow, to traverse the Linked List.
2. Point both the nodes to the head of the Linked List.
3. Iterate using fast pointer, until fast points to (K – 1)th node from the beginning.
4. While traversing, maintain firstPrev to store previous node of fast pointer.
5. Now, increment slow and fast pointers by a node in each iteration, until fast->next becomes equal to NULL.
6. While traversing, maintain secondPrev to store previous node of slow pointer.
7. Delete both the nodes of the Linked List, using firstPrev and secondPrev pointers.
8. Print the updated linked list.

Below is the implementation of the above approach:

## Javascript



Output

1 2 3 4 5 6
1 2 5 6

Time Complexity: O(N)
Space Complexity: O(1)

My Personal Notes arrow_drop_up
Recommended Articles
Page :