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; } } public static ListNode segregate01(ListNode head) { if(head == null || head.next == null) return head; ListNode curr = head; ListNode dummyhead = new ListNode(-1); ListNode zero = dummyhead; ListNode one = new ListNode(-1); ListNode help = one; while(curr!=null){ if(curr.val == 0){ zero.next = curr; zero = zero.next; } else{ help.next = curr; help = curr; } curr = curr.next; } zero.next = one.next; return dummyhead.next; } 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 = segregate01(h1); printList(h1); } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter