C Program For Reversing A Linked List In Groups Of Given Size – Set 1
Last Updated :
14 Mar, 2023
Given a linked list, write a function to reverse every k nodes (where k is an input to the function).
Example:
Input: 1->2->3->4->5->6->7->8->NULL, K = 3
Output: 3->2->1->6->5->4->8->7->NULL
Input: 1->2->3->4->5->6->7->8->NULL, K = 5
Output: 5->4->3->2->1->8->7->6->NULL
Algorithm: reverse(head, k)
- Reverse the first sub-list of size k. While reversing keep track of the next node and previous node. Let the pointer to the next node be next and pointer to the previous node be prev. See this post for reversing a linked list.
- head->next = reverse(next, k) ( Recursively call for rest of the list and link the two sub-lists )
- Return prev ( prev becomes the new head of the list (see the diagrams of an iterative method of this post )
Below is image shows how the reverse function works:
Below is the implementation of the above approach:
C
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node* next;
};
struct Node *reverse ( struct Node *head,
int k)
{
if (!head)
return NULL;
struct Node* current = head;
struct Node* next = NULL;
struct Node* prev = NULL;
int count = 0;
while (current != NULL && count < k)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
count++;
}
if (next != NULL)
head->next = reverse(next, k);
return prev;
}
void push( struct Node** head_ref,
int new_data)
{
struct Node* new_node =
( struct Node*) malloc ( sizeof ( struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void printList( struct Node *node)
{
while (node != NULL)
{
printf ( "%d " , node->data);
node = node->next;
}
}
int main( void )
{
struct Node* head = NULL;
push(&head, 9);
push(&head, 8);
push(&head, 7);
push(&head, 6);
push(&head, 5);
push(&head, 4);
push(&head, 3);
push(&head, 2);
push(&head, 1);
printf ( "Given linked list " );
printList(head);
head = reverse(head, 3);
printf ( "Reversed Linked list " );
printList(head);
return (0);
}
|
Output:
Given Linked List
1 2 3 4 5 6 7 8 9
Reversed list
3 2 1 6 5 4 9 8 7
Complexity Analysis:
- Time Complexity: O(n).
Traversal of list is done only once and it has ‘n’ elements.
- Auxiliary Space: O(n/k).
For each Linked List of size n, n/k or (n/k)+1 calls will be made during the recursion.
Please refer complete article on Reverse a Linked List in groups of given size | Set 1 for more details!
Share your thoughts in the comments
Please Login to comment...