Reverse Alternate K nodes in a Singly Linked ListGiven 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.
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
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)
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
Next TopicWhen should I use a List vs a LinkedList
|
Javatpoint provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India