Q22 PepCoding | Segregate Node Of Linkedlist Over Last Index.

PHOTO EMBED

Thu Jan 19 2023 10:17:46 GMT+0000 (Coordinated Universal Time)

Saved by @Ayush_dabas07

import java.util.*;

class Main {
    public static Scanner scn = new Scanner(System.in);

    public static class ListNode {
        int val = 0;
        ListNode next = null;

        ListNode(int val) {
            this.val = val;
        }
    }

//similiar logic to previous questions
    public static ListNode segregateOnLastIndex(ListNode head) {
        ListNode curr = head;
        int val = 0;
        
        ListNode pivot = null;
        
        while(curr.next!=null)
            curr = curr.next;
            
            val = curr.val;
            
            pivot = curr;
            
            curr = head;
        
        ListNode greater = new ListNode(-1);
        ListNode ghelp = greater;
        
        ListNode smaller = new ListNode(-1);
        ListNode shelp = smaller;
        
        //stopping at last node
        while(curr!= null){
            
            if(curr.val <= val){
                shelp.next = curr;
                shelp = curr;
            }
            else{
                ghelp.next = curr;
                ghelp = curr;
            }
            curr = curr.next;
        }
        
        shelp.next = greater.next;
        ghelp.next = null;
        
        return pivot;
    }

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

    public static ListNode createList(int n) {
        ListNode dummy = new ListNode(-1);
        ListNode prev = dummy;
        while (n-- > 0) {
            prev.next = new ListNode(scn.nextInt());
            prev = prev.next;
        }

        return dummy.next;
    }

    public static void main(String[] args) {
        int n = scn.nextInt();
        ListNode h1 = createList(n);
        h1 = segregateOnLastIndex(h1);
        printList(h1);
    }
}
content_copyCOPY

https://www.pepcoding.com/resources/data-structures-and-algorithms-in-java-levelup/linked-list/segregate-node-of-linkedlist-over-last-index./ojquestion