Skip to content

Instantly share code, notes, and snippets.

@Kishy-nivas
Created April 21, 2018 04:08
Show Gist options
  • Save Kishy-nivas/4c2b3e6c7c1ecd08c742802d90d25f7b to your computer and use it in GitHub Desktop.
Save Kishy-nivas/4c2b3e6c7c1ecd08c742802d90d25f7b to your computer and use it in GitHub Desktop.
/*Please note that it's Function problem i.e.
you need to write your solution in the form of Function(s) only.
Driver Code to call/invoke your function is mentioned above.*/
/* The structure of the node of the Linked List is
class Node
{
int data;
Node next;
Node(int d) {data = d; next = null; }
}
*/
class GfG
{
Node sortedList(Node head)
{
Node curr = head;
Node add = null;
Node add_start = null;
Node sub = null;
Node sub_start = null;
Stack<Integer> stack = new Stack<Integer>();
while(curr != null){
if(curr.data >= 0){
if(add == null){
add = new Node(curr.data);
add_start = add;
}
else{
add.next = new Node(curr.data);
add = add.next;
}
}
else{
stack.push(curr.data);
}
curr = curr.next;
}
if(add != null)
add.next =null;
if(!stack.isEmpty()){
while(!stack.isEmpty()){
int val =stack.pop();
if(sub == null){
sub = new Node(val);
sub_start = sub;
}
else{
sub.next = new Node(val);
sub = sub.next;
}
}
sub.next = add_start;
return sub_start;
}
else{
return add_start;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment