Javatpoint Logo
Javatpoint Logo

Reverse Alternate K nodes in a Singly Linked List

Given a linked list, write a function that efficiently reverses every alternate k node (where k is the function's input).

Example:

Method No. 1 (Process 2k nodes and recursively call for rest of the list)

This approach is essentially an expansion of the one described in this post.

kAltReversed(struct node *head, int k) is a reverse function.

  1. Invert the first k nodes.
  2. The updated list's head node now points to the kth node. So update the next node in the head to the (k+1)th node.
  3. Reposition the current pointer to skip the following k nodes.
  4. Recursively call kAltReversed() for the remaining n - 2k nodes.
  5. Return the list's new head.

C++ program:

Output:

Given linked list 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 
Modified Linked list 
3 2 1 4 5 6 9 8 7 10 11 12 15 14 13 16 17 18 20 19
  • Time Complexity will be O(n).
  • Space Complexity will be O(n).

Method No. 2 (Process k nodes and recursively call for rest of the list)

Method 1 reverses the initial k node and then advances the pointer k nodes. Method 1 utilizes two while loops to handle 2k nodes in a single recursive call.

In a recursive call, this technique only processes k nodes. It employs a third bool argument b to determine if the k items should be reversed or simply moved.

_kAltReversed(struct node *head, int k, bool b)

  1. Reverse the first k nodes if b is true.
  2. If b is false, forward the pointer by k nodes.
  3. Recursively call kAltReversed() for the remaining n - k nodes and connect the rest of the changed list to the end of the first k nodes.
  4. Return the list's new head.

C Program:

C++ Program:

Output:

Given linked list 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 
Modified Linked list 
3 2 1 4 5 6 9 8 7 10 11 12 15 14 13 16 17 18 20 19
  • Time Complexity will be O(n).
  • Space Complexity will be O(n).






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA