Q21 PepCoding | Segregate 01 Node Of Linkedlist Over Swapping Nodes
Thu Jan 19 2023 09:24:26 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;
}
}
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);
}
}
content_copyCOPY
https://www.pepcoding.com/resources/data-structures-and-algorithms-in-java-levelup/linked-list/segregate-01-node-of-linkedlist-over-swapping-nodes/ojquestion
Comments