- Linked List, Reverse

Reverse a singly Linked List in groups of given size | Set 4 (Space efficient approach)

  class LinkedList {          Node head;          class Node {        int data;        Node next;        Node(int d)        {            data = d;            next = null;        }    }      Node reverse(Node node, int k)    {        if (k == 1)            return node;                  Node result = null;                  Node head = new Node(0);        head.next = node;        Node next = node.next;          int count = 0;        while (next != null) {            count++;                                                  Node tmp = next.next;            next.next = node;            node = next;            next = tmp;              if (count == k – 1) {                count = 0;                  if (result == null)                    result = node;                                                                  tmp = head.next;                tmp.next = next;                head.next = node;                head = tmp;                                  node = next;                if (node != null)                    next = node.next;            }        }                  Node tmp = head.next;        if (tmp != null)            tmp.next = null;        head.next = node;          return result;    }                    public void push(int new_data)    {        Node new_node = new Node(new_data);        new_node.next = head;        head = new_node;    }          void printList()    {        Node temp = head;        while (temp != null) {            System.out.print(temp.data + ” “);            temp = temp.next;        }        System.out.println();    }          public static void main(String args[])    {        LinkedList llist = new LinkedList();                           llist.push(8);        llist.push(7);        llist.push(6);        llist.push(5);        llist.push(4);        llist.push(3);        llist.push(2);        llist.push(1);          llist.head = llist.reverse(llist.head, 3);        llist.printList();    }}