How to reverse K alternate nodes in a singly linked list
A singly linked list is a collection of data stored in nodes, each connected to the next using a pointer.
Note: We can read more about singly linked lists here.
To reverse
Illustration
As an example, let's look at the following singly linked list:
Taking
The process for this reversal is illustrated below:
Implementation
The following is a Python implementation of the process illustrated above. The linked list is created in the last highlighted section in lines 35–44.
import linkedListdef reverseKAlternate(k, head):current = head # used to traverse the linked listnext = None # used to change the next pointers when reversing nodesnew_head = None # stores the head of the final linked listcount = 0 # used to ensure we reverse at every K alternate nodeswhile count < k and current != None:count += 1next = current.nextcurrent.next = new_headnew_head = currentcurrent = nextif head != None:head.next = currentcount = 0while count < k - 1 and current != None:count += 1current = current.nextif current != None:current.next = reverseKAlternate(k, current.next)return new_headK = 2original_list = linkedList.linkedList()original_list.insert(1)original_list.insert(2)original_list.insert(3)original_list.insert(4)original_list.insert(5)original_list.insert(6)original_list.insert(7)original_list.insert(8)original_list.insert(9)original_list.insert(10)print("Original Linked List:", end = ' ')original_list.printList()print()final_list = linkedList.linkedList()final_list.head = reverseKAlternate(K, original_list.head)print("Final Linked List:", end = ' ')final_list.printList()
The algorithm operates with the following properties:
Note: We can edit the value of
in line 31.
Explanation
The file linkedList.py contains the definition of the linked list and node class, along with a few helper functions.
The following is happening in the reverseKAlternate.py file:
Lines 3–28: The function
reverseKAlternate(k, head)takes in a value for the number of alternating nodeskalong with the head of the original linked list stored inhead.Lines 9–14: We reverse the first
knodes of the linked list. The valuecountensures we only reverseknodes.Lines 16–17: The value
currentis now the (k+1)th element of the linked list, so the next element after theheadnode will becurrent.Lines 19–23: The next
kelements do not have to be reversed, so we simply traverse past them.Lines 25–26: We replicate the code in lines 9–23 for the rest of the list, starting at
current.next(sincecurrentis the 2kth element), by callingreverseKAlternate()recursively.Line 31: We store the number of alternating nodes in the variable
K.Lines 35–44: We create the original linked list by inserting its nodes individually.
Lines 46–48: We print the original linked list.
Lines 50–54: We call the function
reverseKAlternate()and print the final linked list.
Free Resources