Skip to content

Instantly share code, notes, and snippets.

@Ram-1234
Last active January 3, 2021 03:48
Show Gist options
  • Save Ram-1234/1a27fde6bfc2e8980e4c4932280268ab to your computer and use it in GitHub Desktop.
Save Ram-1234/1a27fde6bfc2e8980e4c4932280268ab to your computer and use it in GitHub Desktop.
AMAZON LINKED LIST
Problem Description
Given a Linked List A consisting of N nodes.
The Linked List is binary i.e data values in the linked list nodes consist of only 0's and 1's.
You need to sort the linked list and return the new linked list.
NOTE:-Try to do it in constant space.
Problem Constraints
1:- 1 <= N <= 105
2:- A.val = 0 or A.val = 1
INPUT:- 1 -> 0 -> 0 -> 1
OUTPUT:- 0 -> 0 -> 1 -> 1
####JAVA CODE
/**
* Definition for singly-linked list.
* class ListNode {
* public int val;
* public ListNode next;
* ListNode(int x) { val = x; next = null; }
* }
*/
public class Solution {
public ListNode solve(ListNode A) {
ListNode curr=A;
ListNode pre=null;
int zero=0;
int one=0;
while(curr!=null){
if(curr.val==1) one++;
if(curr.val==0) zero++;
curr=curr.next;
}
ListNode curr1=A;
while(curr1!=null){
while(zero-->0){
curr1.val=0;
curr1=curr1.next;
}
while(one-->0){
curr1.val=1;
curr1=curr1.next;
}
//curr1=curr1.next
}
return A;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment