Int not able to accomodate the result and hence program fails - java

This is a leetcode problem number 2. I guess I am really dumb not able to solve this. I encountered a particular issue where I am not able to solve it for the test case
[9]
[9,9,9,9,9,9,9,9,9,1]
The issue is that my program is returning 1410065399 instead of 9999999991 when I try to make a digit out of the link list. I have mentioned the actual problem statement and my solution alongside. Please provide some light so that I can understand what went wrong.
PROBLEM
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
Actual Code which I wrote
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
class Solution {
ListNode first;
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int finalResult = returnNumber(l1)+returnNumber(l2);
System.out.println(returnNumber(l1));
System.out.println(returnNumber(l2));
int length=0;
if(finalResult!=0){
length = (int)(Math.log10(finalResult)+1);
}else{
length =1;
}
for(int i=length-1;i>=0;i--){
generateList(finalResult,i);
}
return first;
}
public void generateList(int finalResult,int number){
ListNode oldNode = first;
first = new ListNode((finalResult / (int)Math.pow(10,number)) % 10);
System.out.println((finalResult / (int)Math.pow(10,number)) % 10);
first.next = oldNode;
}
public int returnNumber(ListNode list){
int i=0;
int base = 10;
int total = 0;
while(list!=null){
total=total+(list.val*(int)Math.pow(10,i));
i++;
list = list.next;
}
return total;
}
}
public class MainClass {
public static int[] stringToIntegerArray(String input) {
input = input.trim();
input = input.substring(1, input.length() - 1);
if (input.length() == 0) {
return new int[0];
}
String[] parts = input.split(",");
int[] output = new int[parts.length];
for(int index = 0; index < parts.length; index++) {
String part = parts[index].trim();
output[index] = Integer.parseInt(part);
}
return output;
}
public static ListNode stringToListNode(String input) {
// Generate array from the input
int[] nodeValues = stringToIntegerArray(input);
// Now convert that list into linked list
ListNode dummyRoot = new ListNode(0);
ListNode ptr = dummyRoot;
for(int item : nodeValues) {
ptr.next = new ListNode(item);
ptr = ptr.next;
}
return dummyRoot.next;
}
public static String listNodeToString(ListNode node) {
if (node == null) {
return "[]";
}
String result = "";
while (node != null) {
result += Integer.toString(node.val) + ", ";
node = node.next;
}
return "[" + result.substring(0, result.length() - 2) + "]";
}
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = in.readLine()) != null) {
ListNode l1 = stringToListNode(line);
line = in.readLine();
ListNode l2 = stringToListNode(line);
ListNode ret = new Solution().addTwoNumbers(l1, l2);
String out = listNodeToString(ret);
System.out.print(out);
}
}
}

As the inputs are list instead of an Integer so there isn't a restriction on length of it. So I would suggest looping through the input and collecting the sum of elements as you go through it and creating the result list. (don't forget the carry which can be of multiple digits)
Below you can find my code for reference.
(Any suggestions will always be welcomed)
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = null, node = null;
int carry = 0, sum = 0;
while (!(l1 == null && l2 == null)) {
// both not null
if (l1 != null && l2 != null) {
sum = (l1.val + l2.val + carry) % 10;
carry = (l1.val + l2.val + carry) / 10;
l1 = l1.next;
l2 = l2.next;
}
// l1==null
else if (l1 == null && l2 != null) {
sum = (l2.val + carry) % 10;
carry = (l2.val + carry) / 10;
l2 = l2.next;
}
// l2==null
else if (l1 != null && l2 == null) {
sum = (l1.val + carry) % 10;
carry = (l1.val + carry) / 10;
l1 = l1.next;
}
// both null
else {
// break out of the loop
}
if (head == null) {
head = new ListNode(sum);
node = head;
} else {
node.next = new ListNode(sum);
node = node.next;
}
}
if (carry > 0) {
while (carry > 0) {
int curr = carry % 10;
node.next = new ListNode(curr);
node = node.next;
carry = carry / 10;
}
}
return head;
}

Related

How to implement a maximum priority queue using a heap-ordered binary tree with a triply-linked Node?

I am trying to implement a max priority queue using a heap binary tree with a triple-linked node. This is the code that I currently have yet when I run it and try to print out the tree nothing prints out it is just empty lines. I am using the helped methods sink and swim in order to help me organize the queue as I add different elements. I am also implementing an ADT (MaxPQ) which just has the public methods that need to be implemented. I was wondering if there is anything that I am doing wrong?
public class LinkedMaxPQ<T extends Comparable<T>> implements MaxPQ<T> {
// Instance variables
Node root;
int size;
Node lastInserted;
// Node inner class definition
// Node class
class Node {
int N;
T info;
Node left;
Node right;
Node parent;
Node(T info, int N) {
this.info = info; this.N = N;
}
}
private void swim(Node x){
if(x == null) return;
if(x.parent == null) return; // we're at root
int cmp = x.info.compareTo(x.parent.info);
if(cmp > 0){
swapNodeData(x, x.parent);
swim(x.parent);
}
}
private void swapNodeData(Node x, Node y){
T temp = x.info;
x.info = y.info;
y.info = temp;
}
private void sink(Node x){
if(x == null) return;
Node swapNode;
if(x.left == null && x.right == null){
return;
}
else if(x.left == null){
swapNode = x.right;
int cmp = x.info.compareTo(swapNode.info);
if(cmp < 0)
swapNodeData(swapNode, x);
} else if(x.right == null){
swapNode = x.left;
int cmp = x.info.compareTo(swapNode.info);
if(cmp < 0)
swapNodeData(swapNode, x);
} else{
int cmp = x.left.info.compareTo(x.right.info);
if(cmp >= 0){
swapNode = x.left;
} else{
swapNode = x.right;
}
int cmpParChild = x.info.compareTo(swapNode.info);
if(cmpParChild < 0) {
swapNodeData(swapNode, x);
sink(swapNode);
}
}
}
String printThisLevel (Node rootnode, int level) {
StringBuilder s = new StringBuilder();
// Base case 1: if the current rootnode is null, return the current string.
if (rootnode == null) {
return s.toString();
}
// Base case 2: If you're at the first level, append the
// info field of the current rootnode.
if (level == 1) {
s.append( rootnode.info.toString());
}
// Recursive calls: otherwise call the method on the left
// and on the right of the next lower level.
else if (level > 1) {
s.append( printThisLevel(rootnode.left, level-1));
s.append( printThisLevel(rootnode.right, level-1));
}
return s.toString();
}
private int size(Node x){
if(x == null) return 0;
return x.N;
}
private Node insert(Node x, T data){
if(x == null){
lastInserted = new Node(data, 1);
return lastInserted;
}
// compare left and right sizes see where to go
int leftSize = size(x.left);
int rightSize = size(x.right);
if(leftSize <= rightSize){
// go to left
Node inserted = insert(x.left, data);
x.left = inserted;
inserted.parent = x;
} else{
// go to right
Node inserted = insert(x.right, data);
x.right = inserted;
inserted.parent = x;
}
x.N = size(x.left) + size(x.right) + 1;
return x;
}
private Node resetLastInserted(Node x){
if(x == null) return null;
if(x.left == null && x.right == null) return x;
if(size(x.right) < size(x.left))return resetLastInserted(x.left);
else return resetLastInserted(x.right);
}
public void insert(T data){
root = insert(root, data);
swim(lastInserted);
}
public T getMax(){
if(root == null) return null;
return root.info;
}
public T removeMax(){
if(size() == 1){
T ret = root.info;
root = null;
return ret;
}
swapNodeData(root, lastInserted);
Node lastInsParent = lastInserted.parent;
T lastInsData = lastInserted.info;
if(lastInserted == lastInsParent.left){
lastInsParent.left = null;
} else{
lastInsParent.right = null;
}
Node traverser = lastInserted;
while(traverser != null){
traverser.N--;
traverser = traverser.parent;
}
lastInserted = resetLastInserted(root);
sink(root);
return lastInsData;
}
public int size(){
return size(root);
}
public boolean isEmpty(){
return size() == 0;
}
public String toString() {
// Create a StringBuilder object to make it more efficient.
StringBuilder sb=new StringBuilder();
// get the height of the tree
int height = (int)Math.ceil(Math.log(size+1) / Math.log(2));
// for each level in the tree, call printThisLevel and
// append the output to the StringBuilder
for (int i=1; i<=height; i++) {
sb.append("level " + i + ": "+ printThisLevel(this.root, i) + "\n");
}
// Return the string of the StringBuilder object
return sb.toString();
}
public static void main (String[] args) {
LinkedMaxPQ<String> t = new LinkedMaxPQ<String>();
t.insert("a");
System.out.println(t.toString());
t.insert("b");
t.insert("c");
t.insert("d");
t.insert("e");
t.insert("f");
t.insert("g");
t.insert("h");
t.insert("i");
t.insert("j");
t.insert("k");
t.size();
t.removeMax();
t.getMax();
t.removeMax();
t.insert("x");
t.insert("y");
t.removeMax();
t.getMax();
System.out.println(t.toString());
}
}
In this line:
int height = (int)Math.ceil(Math.log(size+1) / Math.log(2));
size should be size().
int height = (int)Math.ceil(Math.log(size()+1) / Math.log(2));
After this correction, the results are coming out.
However, there is a logic problem, which needs a solution.
For test case, testdata = new int[] {3, 5, 2, -7, 9, 4, 7};
The result is 9 4 7 -7 3 2 5
But correct result should be 9 5 7 -7 3 2 4 (from another array implementation).
I know the mistake comes from when at the 3rd levle, insert data {9}, its parent should be the 2nd leverl data {3} on the left, not the {2} on the right. Any thought to solve it?

Combining Like Terms/ LinkedList Polynomial [Java]

So my issue here is getting this program to combine like terms, I've tried about 3 different ways of going about this and cannot figure it out. I can sort the array in somewhat the correct order but not get it to combine.
public static Node multiply(Node poly1, Node poly2) {
Node polynomial1 = poly1;
Node polynomial2 = poly2;
Node mult = poly2;
Node temp3 = null;
float cmb = 0;
int cmbExp = 0;
// the sum of the polynomials
Node temp = null;
float coeffProd;
int expSum;
if(poly1 == null)
return "Enter a Different Polynomial";
if(poly2 == null)
return "Enter a Different Polynomial";
// while loop if either polynomial runs out of terms. This avoids nullpointerexception
while (polynomial1 != null) {
while(polynomial2 != null){
coeffProd = polynomial1.term.coeff * polynomial2.term.coeff;
expSum = polynomial1.term.degree + polynomial2.term.degree;
temp = new Node(coeffProd, expSum, temp);
polynomial2 = polynomial2.next;
}
polynomial1 = polynomial1.next;
polynomial2 = mult;
}
// my attempt at combining
Node temp2 = temp.next;
while(temp != null){
while(temp2 != null){
if(temp.term.degree == temp2.term.degree){
cmb = temp.term.coeff + temp2.term.coeff;
cmbExp = temp.term.degree;
}
temp2 = temp2.next;
temp3 = new Node(cmb,cmbExp,temp3);
}
temp = temp.next;
}
// Reverses the Polynomial into the correct sequence
Node flip = temp;
Node ans = null;
while (flip != null)
{
if (flip.term.coeff == 0)
{
flip = flip.next;
continue;
}
else
{
ans = new Node(flip.term.coeff, flip.term.degree, ans);
flip = flip.next;
}
}
if (ans == null)
return null;
else
{
return ans;
}
}
Result:
32.0x^9 + 16.0x^8 + -12.0x^6 + 36.0x^5 + -16.0x^7 + -8.0x^6 + 6.0x^4 + -18.0x^3 + 16.0x^5 + 8.0x^4 + -6.0x^2 + 18.0x + 24.0x^4 + 12.0x^3 + -9.0x + 27.0
I need to combine these like terms.
The combining can be simplified if you iterate through the degrees. This also guarantees that the combined polynomial is created with the degrees in sequential order.
The following working code demonstrates one possible way to combine, and create the desired result.
public Node multiply(Node poly1, Node poly2) {
if (poly1 == null || poly2 == null)
return null;
Node polynomial1 = poly1;
Node polynomial2 = poly2;
Node allTerms = null;
float coeffProd;
int expSum;
int maxDegree = 0;
while (polynomial1 != null) {
while (polynomial2 != null) {
coeffProd = polynomial1.term.coeff * polynomial2.term.coeff;
expSum = polynomial1.term.degree + polynomial2.term.degree;
allTerms = new Node(coeffProd, expSum, allTerms);
if (expSum > maxDegree)
maxDegree = expSum;
polynomial2 = polynomial2.next;
}
polynomial1 = polynomial1.next;
polynomial2 = poly2;
}
/* Combine terms */
Node combinedNode = null;
for (int i = 0; i<= maxDegree; i++) {
Node temp = allTerms;
float fSum = 0;
while (temp != null) {
if (temp.term.degree == i)
fSum+=temp.term.coeff;
temp = temp.next;
}
if (fSum != 0)
combinedNode = new Node(fSum, i, combinedNode);
}
return combinedNode;
}

Can't print out Add two numbers in Java

I can't return the value from the function AddTwoNumber to main. I have already checked the result in the function and it is correct. However, when I pass the value from AddTwoNumber into ListNode start, it doesn't print anything. I think the problem is happening here:
ListNode dummy = new ListNode(0);
ListNode node = dummy;
but I'm don't know how to solve it.
ListNode.cs:
class ListNode {
public int data; // data stored in this node
public ListNode next; // link to next node in the list
// post: constructs a node with data 0 and null link
public ListNode() {
this(0, null);
}
// post: constructs a node with given data and null link
public ListNode(int data) {
this(data, null);
}
// post: constructs a node with given data and given link
public ListNode(int data, ListNode next) {
this.data = data;
this.next = next;
}
}
Main.cs:
public static void main(String[] args) {
ListNode first = new ListNode(8,
new ListNode(9,
new ListNode(7 )));
ListNode second = new ListNode(3,
new ListNode(5,
new ListNode(6 )));
ListNode start = AddTwoNumber(first,second);
while (start!=null) {
System.out.println(start.next);
start=start.next;
}
}
public static ListNode AddTwoNumber(ListNode first, ListNode second) {
ListNode dummy = new ListNode(0);
ListNode node = dummy;
int Digitsten = 0;
int sum = 0;
//Once fit first&second =null & Digitsten=0,the code can stop
while (first != null || second != null || Digitsten != 0) {
if (first != null && second != null) {
sum += first.data + second.data + Digitsten;
} else if (first!= null) {
sum += first.data + Digitsten;
} else if (second!= null) {
sum += second.data + Digitsten;
} else {
sum=Digitsten; `enter code here`
}
int DigitsOne = sum % 10;
Digitsten = sum / 10;
node = new ListNode(DigitsOne);
node = node.next;
if (first == null) {
first = null;
} else {
first = first.next;
}
if (second == null) {
second = null;
} else {
second = second.next;
}
sum = 0;
}
return dummy.next; //return the value to dummy ListNode
}
The real problem is inside your AddTwoNumber method.
You can't make node pointing to a new node, you should make its next pointing to a new node, before you move to next.
public static ListNode AddTwoNumber(ListNode first, ListNode second){
ListNode dummy = new ListNode(0);
ListNode node = dummy;
int Digitsten = 0;
int sum = 0;
while (first != null || second != null || Digitsten != 0)
{
if (first != null && second != null)
{
sum += first.data + second.data + Digitsten;
}
else if (first!= null)
{
sum += first.data + Digitsten;
}
else if (second!= null)
{
sum += second.data + Digitsten;
}
else
{
sum=Digitsten; `enter code here`
}
int DigitsOne = sum % 10;
Digitsten = sum / 10;
// LOOK HERE!!!
node.next = new ListNode(DigitsOne);
node = node.next;
if (first == null)
{
first = null;
}
else
first = first.next;
if (second == null)
{
second = null;
}
else
{
second = second.next;
}
sum=0;
}
return dummy.next;//return the value to dummy ListNode

Adding two numbers given (digits in Linked List) using Strings

I am trying to add two non negative numbers, the digits of which are stored in reverse order in two separate linked lists. The answer should also be a linked list with digits reversed and no trailing zeros.
I understand that there is a way to solve this question by adding digits and maintaining a carry each time, but I am trying to solve it by using addition operation on numbers.
Here's my 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 addTwoNumbers(ListNode a, ListNode b) {
if(a==null || b==null){
return null;
}
String num1 = "";
String num2 = "";
ListNode temp1 = a;
ListNode temp2 = b;
while(temp1!=null){
num1 = num1+Integer.toString(temp1.val);
temp1 = temp1.next;
}
new StringBuilder(num1).reverse().toString();
double value1 = Double.parseDouble(num1);
while(temp2!=null){
num2 = num2+Integer.toString(temp2.val);
temp2 = temp2.next;
}
new StringBuilder(num2).reverse().toString();
double value2 = Double.parseDouble(num2);
double result = value1+value2;
String res = String.format("%.0f",result);
ListNode first_node = new ListNode(Character.getNumericValue(res.charAt(0)));
ListNode ans = first_node;
for(int j=1;j<res.length();j++){
ListNode node = new ListNode(Character.getNumericValue(res.charAt(j)));
add(node,ans);
}
return ans;
}
public void add(ListNode node, ListNode ans){
ListNode temp;
temp = ans;
ans = node;
ans.next = temp;
}
}
My code has been giving wrong answers. Can anyone point out the errors?
Your approach is not correct and indirect.
You are trying to do big numbers arithmetics using floating point operations.
As a result - computing errors.
We have:
List<Integer> firstNumber;
List<Integer> secondNumber;
Lets assume firstNumber > secondNumber.
Try this alogrithm:
List<Integer> result = new ArrayList<>();
int i = 0;
int appendix = 0;
for (; i < secondNumber.size(); i++) {
int sum = firstNumber.get(i) + secondNumber.get(i) + appendix;
result.append(sum % 10);
appendix = sum / 10;
}
for (; i < firstNumber.size(); i++) {
int sum = firstNumber.get(i) + appendix;
result.append(sum % 10);
appendix = sum / 10;
}
if (appendix != 0)
result.append(appendix);
return result;
Your add function looks incorrect. You will get you number in the reverse order than what is expected.
Also, your solution is missing the point of the question. Your approach will fail if you have a number with a lot of digits (even double has its limits ~ 2^1024 I think). A linked list representation allows for numbers even bigger.
The correct solution would just iterate through both the lists simultaneously with a carry digit while creating the solution list. If this is a question in an assignment or coding competition, your solution would be judged wrong.
Your add method is wrong, it doesn't build correctly the list. Here is how the final part of your method should look, without the add method:
for(int j=1;j<res.length();j++){
ans.next = new ListNode(Character.getNumericValue(res.charAt(j)));;
ans = ans.next;
}
return first_node;
In your approach, the variable ans is not updating. You can try this:
ans = add(node,ans);
and in your add method, change the method to return ListNode ans
Your approach is not straightforward and wouldn't give you expected results.
Here is a simple approach which wouldn't require much explanation as the addition is simple integer by integer.
Do note that i carry forward when the sum of two integers is greater than 9 else continue with the sum of next integers from both the list.
class Node {
private Object data;
private Node next;
public Object getData() { return data; }
public void setData(Object data) { this.data = data; }
public Node getNext() { return next; }
public void setNext(Node next) { this.next = next; }
public Node(final Object data, final Node next) {
this.data = data;
this.next = next;
}
#Override
public String toString() { return "Node:[Data=" + data + "]"; }
}
class SinglyLinkedList {
Node start;
public SinglyLinkedList() { start = null; }
public void addFront(final Object data) {
// create a reference to the start node with new data
Node node = new Node(data, start);
// assign our start to a new node
start = node;
}
public void addRear(final Object data) {
Node node = new Node(data, null);
Node current = start;
if (current != null) {
while (current.getNext() != null) {
current = current.getNext();
}
current.setNext(node);
} else {
addFront(data);
}
}
public void deleteNode(final Object data) {
Node previous = start;
if (previous == null) {
return;
}
Node current = previous.getNext();
if (previous != null && previous.getData().equals(data)) {
start = previous.getNext();
previous = current;
current = previous.getNext();
return;
}
while (current != null) {
if (current.getData().equals(data)) {
previous.setNext(current.getNext());
current = previous.getNext();
} else {
previous = previous.getNext();
current = previous.getNext();
}
}
}
public Object getFront() {
if (start != null) {
return start.getData();
} else {
return null;
}
}
public void print() {
Node current = start;
if (current == null) {
System.out.println("SingleLinkedList is Empty");
}
while (current != null) {
System.out.print(current);
current = current.getNext();
if (current != null) {
System.out.print(", ");
}
}
}
public int size() {
int size = 0;
Node current = start;
while (current != null) {
current = current.getNext();
size++;
}
return size;
}
public Node getStart() {
return this.start;
}
public Node getRear() {
Node current = start;
Node previous = current;
while (current != null) {
previous = current;
current = current.getNext();
}
return previous;
}
}
public class AddNumbersInSinglyLinkedList {
public static void main(String[] args) {
SinglyLinkedList listOne = new SinglyLinkedList();
SinglyLinkedList listTwo = new SinglyLinkedList();
listOne.addFront(5);
listOne.addFront(1);
listOne.addFront(3);
listOne.print();
System.out.println();
listTwo.addFront(2);
listTwo.addFront(9);
listTwo.addFront(5);
listTwo.print();
SinglyLinkedList listThree = add(listOne, listTwo);
System.out.println();
listThree.print();
}
private static SinglyLinkedList add(SinglyLinkedList listOne, SinglyLinkedList listTwo) {
SinglyLinkedList result = new SinglyLinkedList();
Node startOne = listOne.getStart();
Node startTwo = listTwo.getStart();
int carry = 0;
while (startOne != null || startTwo != null) {
int one = 0;
int two = 0;
if (startOne != null) {
one = (Integer) startOne.getData();
startOne = startOne.getNext();
}
if (startTwo != null) {
two = (Integer) startTwo.getData();
startTwo = startTwo.getNext();
}
int sum = carry + one + two;
carry = 0;
if (sum > 9) {
carry = sum / 10;
result.addRear(sum % 10);
} else {
result.addRear(sum);
}
}
return result;
}
}
Sample Run
Node:[Data=3], Node:[Data=1], Node:[Data=5]
Node:[Data=5], Node:[Data=9], Node:[Data=2]
Node:[Data=8], Node:[Data=0], Node:[Data=8]

How to sort a linked list of Polynomials by degree?

Currently I've written a method that adds two polynomials together. Poly1 and Poly2. The logic of the method is as follows, first it adds all matching degree terms from Poly1 and Poly2, then it adds all non-matching terms from Poly1, and finally adds all non-matching terms from Poly2. But because of this, the terms are out of order.
Polynomial answer = new Polynomial();
for (Node firstPoly = poly; firstPoly != null; firstPoly = firstPoly.next){
boolean polyAdded = false;
for (Node secondPoly = p.poly; secondPoly != null; secondPoly = secondPoly.next){
if (firstPoly.term.degree == secondPoly.term.degree){
answer = addToRear(answer, (firstPoly.term.coeff + secondPoly.term.coeff), firstPoly.term.degree, null);
if (answer.poly.term.coeff == 0){
answer.poly = null;
}
polyAdded = true;
}
}
if (polyAdded == false){
answer = addToRear(answer, firstPoly.term.coeff, firstPoly.term.degree, null);
if (answer.poly.term.coeff == 0){
answer.poly = null;
}
}
}
for (Node secondPoly = p.poly; secondPoly != null; secondPoly = secondPoly.next){
boolean match = false;
for (Node answerPoly = answer.poly; answerPoly != null; answerPoly = answerPoly.next){
if (secondPoly.term.degree == answerPoly.term.degree){
match = true;
break;
}
}
if (match == false){
answer = addToRear(answer, secondPoly.term.coeff, secondPoly.term.degree, null);
}
}
return answer;
//alt + shift + r
}
If this code outputs:
8.0x^4 + 4.0x^5 + 2.0x^3 + -1.0x + 12.0
the linked list is represented as such:
(coefficient, degree) // (12, 0) -> (-1, 1) -> (2, 3) -> (4, 5) -> (8, 4)
I want to now sort my answer polynomial by order of degree. The linked list should be represented like this:
(coefficient, degree) // (12, 0) -> (-1, 1) -> (2, 3) -> (8, 4) -> (4, 5)
EDIT: Found the solution on my own. Here is the sorting method I created:
private Polynomial sortByDegree(Polynomial p){
Node prev = p.poly;
Node current = p.poly.next;
while (current != null){
if (current.term.degree < prev.term.degree){
int temp = current.term.degree;
current.term.degree = prev.term.degree;
prev.term.degree = temp;
float temp2 = current.term.coeff;
current.term.coeff = prev.term.coeff;
prev.term.coeff = temp2;
prev = p.poly;
current = p.poly.next;
}
prev = prev.next;
current = current.next;
}
return p;
}
Thanks everyone!
Can suggest two approaches:
First. Fetch linked list into array list (stack), sort array list, rebuild as linked list.
Second. Use following algo:
void sortPoly(Polynomial answer) {
float lowerMargin = 0;
Node head = null, tail = null;
while (answer.poly != null) {
Node next = detouchMin(lowerMargin, answer);
lowerMargin = next.term.degree;
if (tail != null) {
tail.next = next;
tail = next;
else {
head = next;
tail = next;
}
}
answer.poly = head;
}
Node detouchMin(float lowerMargin, Polynomial answer) {
float min = Float.inf;
Node n = null;
Node t = answer.poly;
while (t != null) {
if ((t.term.degree > lowerMargin) && (t.term.degree < min)) {
n = t;
min = n.term.degree;
}
t = t.next;
}
if (n != null) {
Node t = answer.poly, prev = null;
while (t != null) {
if (t == n) {
if (prev != null)
answer.poly = t.next;
else
prev.next = t.next;
}
prev = t;
t = t.next;
}
}
return n;
}
Note: code not tested

Categories

Resources