Skip to content

Instantly share code, notes, and snippets.

@ketankhairnar
Created July 26, 2020 08:33
Show Gist options
  • Save ketankhairnar/149f9d419f9813381165cfaffa46ebc8 to your computer and use it in GitHub Desktop.
Save ketankhairnar/149f9d419f9813381165cfaffa46ebc8 to your computer and use it in GitHub Desktop.
package co.in.shoonya.abc.prep.ds.lists;
import co.in.shoonya.abc.prep.ds.lists.ds.ListNode;
public class AggregateAtZeroNode {
public static void main(String[] args) {
ListNode<Integer> l1 = new ListNode<Integer>(1);
l1.setNext(new ListNode<Integer>(4));
l1.getNext().setNext(new ListNode<Integer>(0));
l1.getNext().getNext().setNext(new ListNode<Integer>(0));
l1.getNext().getNext().getNext().setNext(new ListNode<Integer>(2));
l1.getNext().getNext().getNext().getNext().setNext(new ListNode<Integer>(2));
l1.getNext().getNext().getNext().getNext().getNext().setNext(new ListNode<Integer>(0));
l1.getNext().getNext().getNext().getNext().getNext().getNext().setNext(new ListNode<Integer>(7));
System.out.println("aggregateAtZero::b4\t" + l1);
System.out.println("aggregateAtZero::4\t" + aggregateAtZero(l1));
}
private static ListNode<Integer> aggregateAtZero(ListNode<Integer> input) {
int currSum = 0;
int marker = 0;
ListNode<Integer> prev = input;
ListNode<Integer> curr = input;
while (curr != null) {
currSum += curr.getData();
if (curr.getData() == marker) {
prev.setData(currSum);
prev.setNext(curr.getNext());
prev = prev.getNext();
currSum = 0;
}
curr = curr.getNext();
}
return input;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment