Reverse every k nodes of a linked list

Given a linked list and a number k. Reverse every k nodes in the list.

Example :

Input 1->2->3->4->5->6 and k = 2
Output 2->1->4->3->6->5

Solution : We have a pointer q which points to the head of the list initially. Advance this k times in a while loop and keep reversing the list. Now q points to (k+1)th node and we call the same procedure on it. This function returns the head of the reversed list.

struct node *reverseKNodes (struct node *head, int k)
    struct node* q = head;
    struct node* r = NULL;
    struct node* s;
    int count = 0;
    while (q != NULL && count < k)
       s = r;
       r = q;
       q  = q->next;
       r->next = s;
    if(q !=  NULL)
         head->next = reverseKNodes(q, k);
    return r;

3 Thoughts on “Reverse every k nodes of a linked list

  1. Thanks.

    struct node* reverseKNodes(node* head, int k) {
    node* cur = head;
    node* prev = NULL;
    node* next;
    int count = 0;

    while(cur != NULL && count next;
    cur->next = prev;
    prev = cur;
    cur = next;

    if(cur!=NULL) {
    head->next = reverseKNodes(cur, k);

    return prev;

  2. RaghuNathan on March 3, 2015 at 11:54 pm said:

    temp = NULL;
    int value,nextValue ,count=0;

    number can be any value.

    temp = head -> next;
    value = head -> value;
    nextValue = temp -> value;

    if(count value = nextValue;
    temp -> value = value;

    count ++;
    head = head-> next;

  3. Aayush Jain on May 29, 2015 at 4:44 am said:

    I just wanted to know that can we use the Stack data structure to reverse the elements of the list? Does that affect the time complexity as compared to the solution posted here?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Post Navigation