Q5 | Unfold Of Linkedlist

PHOTO EMBED

Fri Jan 06 2023 11:51:54 GMT+0000 (Coordinated Universal Time)

Saved by @Ayush_dabas07

import java.util.*;

class Main {
    public static class Node {
        int val = 0;
        Node next = null;

        Node(int val) {
            this.val = val;
        }
    }
    public static Node mid(Node head){
        Node slow = head;
        Node fast = head;
        int count = 0;
        while(fast.next!= null && fast.next.next != null){
            slow = slow.next;
            fast = fast.next.next;
            count ++;
        }
        return slow;
    }
    public static Node reverse(Node head){
        Node prev = null;
        Node next = null;
        Node curr = head;
        
        while(curr != null){
            next = curr.next;
            curr.next = prev;
            
            prev = curr;
            curr = next;
        }
        return prev;
    }
    public static void unfold(Node head) {
        if(head == null || head.next ==null)
        return;
        
        Node fh = head; //first head
        Node sh = head.next;    //second head
        
        Node fp = head;     //first pointer
        Node sp = head.next;    //second pointer
        
        
        
        while(sp!=null && sp.next!= null){
            Node forward = sp.next;
            
            fp.next= forward;
            sp.next = forward.next;
            
            fp = forward;
            sp = forward.next;
            
        }
        
        //fp is at the last node of first LL
        sh = reverse(sh);
        
        fp.next = sh;
        
    }

    static void printList(Node node) {
        while (node != null) {
            System.out.print(node.val + " ");
            node = node.next;
        }
    }

    public static void main(String[] args) {
        Scanner scn = new Scanner(System.in);
        int n = scn.nextInt();
        Node dummy = new Node(-1);
        Node prev = dummy;
        while (n-- > 0) {
            prev.next = new Node(scn.nextInt());
            prev = prev.next;
        }

        Node head = dummy.next;
        unfold(head);
        printList(head);
    }
}
content_copyCOPY

https://www.pepcoding.com/resources/data-structures-and-algorithms-in-java-levelup/linked-list/unfold-of-linkedlist/ojquestion