This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have created a data structure to to reperesent polynomials using a homegrown node class. I have methods to add and subtract two polynomials of length n. I am trying to add a multiplication method which will return the product of the two polynomials. I am almost finished the problem. At this point I am trying to create a third linked list (using the Node class) in order to store and return the product of the two polynomials. My problem is just coding this solution. I am getting null pointer exception.
Here is my complete code for the Node class:
public class Node{
//Fields
public int data1;
public int data2;
public Node next;
//constructors
public Node(){
data1 = 0;
data2 = 0;
next = null;
}
public Node(int d1){
data1 = d1;
data2 = 0;
next = null;
}
public Node(int d1, Node n){
data1 = d1;
data2 = 0;
next = n;
}
public Node(int d1, int d2){
data1 = d1;
data2 = d2;
next = null;
}
public Node(int d1,int d2, Node n){
data1 = d1;
data2 = d2;
next = n;
}
//Methods
//Fetch data
public int getData1(){
return data1;
}
public int getData2(){
return data2;
}
//store Data
public void setData1(int d){
data1 = d;
}
public void setData2(int d){
data2 = d;
}
public int addData1(Node n2){
data1 = data1 + n2.data1;
return data1;
}
public int addData2(Node n2){
data2 = data2 + n2.data2;
return data2;
}
public void subData1(Node n2){
data1 = data1 - n2.data1;
}
public int multiplyData1(Node n2){
data1 = data1*n2.data1;
return data1;
}
//getNext
public Node getNext(){
return next;
}
//Get data of next node
public int getNextData1(){
return next.data1;
}
public int getNextData2(){
return next.data2;
}
//Store Link
public void setNext(Node n){
next = n;
}
public boolean containsLink(){
if(this.next != null){
return true;
}else{
return false;
}
}
public static void displayAll(Node head){
for( ; head != null; head = head.next ){
System.out.printf("%d, %d\n", head.data1, head.data2);
}
}
public static int numOfNonZeroData1(Node n){
int count = 0;
for( ; n != null ; n = n.next ){
if(n.data1 != 0){
count++;
}
}
return count;
}
public static int numOfNonZeroData2(Node n){
int count = 0;
for( ; n != null ; n = n.next ){
if(n.data2 != 0){
count++;
}
}
return count;
}
public static int listLength(Node head){
int counter = 0;
for(; head!=null; head = head.next){
counter++;
}
return counter;
}
//copy list [Recursive method found on website StackOverflow.com]
public Node copyData1( Node p ) {
if( p == null )
return null;
else
return new Node(p.data1, copyData1(p.next));
}
public Node copyData2( Node p ) {
if( p == null )
return null;
else
return new Node(p.data2, copyData2(p.next));
}
//===============================================================
public static void toPolynomial(Node head){
int order = Node.listLength(head);
int i = 0;
int increment = Node.numOfNonZeroData2(head);
for( ; head != null; head = head.next){
if(head.data2 != 0 && head.data1 != 0){
if(i >= 0 && i < order){
System.out.printf("%dx^%d", head.data1, head.data2);
i++;
if(i < increment && head.data1 >= 0){
System.out.print("+"); //case integer is positive
}else if(i != increment && head.data1 <= 0){
System.out.println(" "); //case integer is negative
}
}
}
}
System.out.println();
}
public static Node mergeLists(Node n1, Node n2){
if ( n1 == null)
return n2;
else if ( n2 == null)
return n1;
else {
n1.next = mergeLists( n1.next, n2 );
return n1;
}
}
public static Node addPolynomials(Node n1, Node n2) {
Node x = n1;
Node y = n2;
for(x = n1; x != null; x = x.next){
for(y = n2; y != null; y = y.next){
if(x.getData2() == y.getData2()){
x.addData1(y);
System.out.println("Added " + (x.data1 - y.data1) + " and " + y.data1);
}
}
}
System.out.println("Add completed");
return x;
}
public static Node subtractPolynomials(Node n1, Node n2){
Node x = n1;
Node y = n2;
for(x = n1; x != null; x = x.next){
for(y = n2; y != null; y = y.next){
if(x.getData2() == y.getData2()){
x.subData1(y);
System.out.println("Subtracted " + (x.data1 - y.data1) + " and " + y.data1);
}
}
}
System.out.println("Subtract completed");
return x;
}
public static Node multiplyPolynomials(Node n1, Node n2){
Node x = n1;
Node y = n2;
Node z = new Node();
for(x = n1; x != null; x = x.next){
for(y = n2; y != null; y = y.next){
z.data1 = x.multiplyData1(y); // error is here
z.data2 = x.addData2(y);
//System.out.println("Multiplied " + (x.data1 - y.data1) + " and " + y.data1);
z = z.next;
}
}
System.out.println("Multiplication completed");
return x;
}
}
Any Ideas?
Please look at this section:
**Node z = new Node();**
for(x = n1; x != null; x = x.next){
for(y = n2; y != null; y = y.next){
z.data1 = x.multiplyData1(y);
z.data2 = x.addData2(y);
//System.out.println("Multiplied " + (x.data1 - y.data1) + " and " + y.data1);
**z = z.next;**
}
}
You are iterating over a list of nodes of any length, but the new z node has a length of 1. You need to be adding nodes to z as you go along. Something like:
z.next = new Node();
z = z.next;
Related
I'm trying to write a program that will go forwards in a circular doubly linked list a certain amount of times and backwards in the same list a certain amount of times. If both methods end up at the same number then the number is 'worthy' and is removed from the list. If the methods don't end up at the same element on the list then they are unworthy and are removed from the list as well. I've written the method for going forwards and backwards a certain amount of times but I'm having difficulty with removing the elements once they have been deemed worthy or unworthy. This is what I have so far. Any help would be greatly appreciated.
import java.util.Arrays;
public class LinkedList {
private Node head;
private Node end;
LinkedList(){
head = end = null;
}
public void addAtStart(int x){
if (head == null) {
Node new_node = new Node(x);
new_node.data = x;
new_node.next = new_node.prev = new_node;
head = new_node;
} else if (head != null) {
Node last = (head).prev;
Node new_node = new Node(x);
new_node.data = x;
new_node.next = head;
(head).prev = new_node;
new_node.prev = last;
last.next = new_node;
}
}
public void printOutput(int N, int k, int m){
System.out.println("Output" + "\n" + "------" + "\n");
printCandidates(N,k,m);
}
public void printCandidates(int N, int k, int m){
int unworthy[] = new int[N];
int worthy[] = new int[N];
int count = 0;
int run = 0;
Node temp = head;
do {
if (forwards(k) == backwards(m)){ // puts in worthy list and deletes from linked list
worthy[count] = forwards(k);
count += 1;
System.out.println("hello");
deleteElement(forwards(k));
} else if (forwards(k) != backwards(m)){ //put in unworthy list and delete from linked list
unworthy[run] = forwards(k);
unworthy[run+1] = backwards(m);
run += 2;
System.out.println("goodbye");
deleteElement(forwards(k));
deleteElement(backwards(m));
}
} while (temp != null);
System.out.println("Removed candidates from being elected");
System.out.println(Arrays.toString(unworthy));
System.out.println("Worthy candidates");
System.out.println(Arrays.toString(worthy));
}
int forwards(int k){
int run = 0;
int x = 0;
Node temp = head;
while (temp.next != head){
if(run == (k)){
x = temp.data;
}
temp = temp.next;
run += 1;
}
return x;
}
int backwards(int m){
int run = 0;
int x = 0;
Node temp = head;
Node last = head.prev;
temp = last;
while (temp.next != head){
if(run == (m)){
x = temp.data;
}
temp = temp.next;
run += 1;
}
return x;
}
public void deleteElement(int elementToBeDeleted){
Node temp = head;
while (temp.next != head){
if(temp.data == elementToBeDeleted){
temp.setNext(temp.next);
}
temp = temp.next;
}
}
This is my driver:
public class Program2 {
public static void main(String[] args) {
LinkedList ll = new LinkedList();
for (int i = 1; i < 11; i++){
ll.addAtStart(i);
}
int N = 10;
int k = 4;
int m = 3;
System.out.println("N = " + N + ", " + "k = " + k + ", " + "m = " + m + "\n");
ll.printOutput(N,k,m);
}
}
This is my node class:
public class Node {
public int data;
public Node next;
public Node prev;
// Constructor to intialize/fill data
public Node(int data){
this.data = data;
}
// set the address of next node
public void setNext(Node temp) {
this.next = temp;
}
// get the address of next node
public Node getNext(){
return this.next;
}
public Node getPrev(){
return this.prev;
}
public void setPrev(Node temp) {
this.prev = temp;
}
// to get data of current node
public int getData(){
return this.data;
}
}
EDIT: As part of this exercise I need to write the class myself, therefore why I am implementing my own LinkedList.
hello i am trying to generate a random doubly linkedlist but i have to insert the node with a negative value and its next node(value doesnt matter) to the HEAD of the list but when i compile the program i am stuck in an infinite loop with one repeating number.I think i connected the list wrong but i am not sure. For context LC is the NODE class, tete is head queue is tail, prev and suiv and next and previous pointer.
class LC {
public int data;
public LC suiv;
public LC prec;
}
public class ChainesDouble {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Détermine an even number N between 10 and 30
int N = (int)(Math.random()*16)+5;
N = (N*2);
System.out.println("La valeur de N = " + N);
// Create a doubly linkedlist with N elements
LC tete = null;
LC queue = null;
for (int i = 0; i < N/2; i++) {
int valeur = getRandom();
int next = getRandom();
//If the generated number is negative insert that number and
//next value into the head of the list
if(valeur <0) {
LC temp = new LC();
temp.data = valeur;
if(tete == null) {
queue = temp;
}
temp = new LC();
temp.data = next ;
tete.prec = temp ;
temp.suiv = tete ;
tete = temp ;
tete.prec = temp ;
temp.suiv = tete ;
tete = temp ;
//If the number is positive, insert the element and the
//next element into the TAIL of the list
}
else {
LC temp = new LC();
temp.data = valeur;
if(queue == null) {
tete = temp;
queue = temp;
}else {
temp.prec = queue;
queue.suiv = temp ;
queue = temp ;
}
temp.prec = queue;
queue.suiv = temp ;
queue = temp ;
}
}
public static int getRandom(){
int N = (int)(Math.random()*42);
if(N<21) {
N -=30;//Rand(-10;-30)
}
else {
N-=11;//Rand(10;30)
}
return N;
}
}
public static void main(String[] args) {
Random random = new Random();
int halfSize = random.nextInt(30) + 1;
ListNode head = createLinkedList(halfSize, random);
System.out.println(printToString(head));
}
private static String printToString(ListNode node) {
StringBuilder buf = new StringBuilder();
while (node != null) {
if (buf.length() > 0)
buf.append("->");
buf.append(node.value);
node = node.next;
}
return buf.toString();
}
public static ListNode createLinkedList(int halfSize, Random random) {
ListNode head = null;
ListNode tail = null;
for (int i = 0; i < halfSize; i++) {
int one = getRandomValue(random);
int two = getRandomValue(random);
if (one >= 0) {
tail = addTail(one, tail);
head = head == null ? tail : head;
tail = addTail(two, tail);
} else {
head = addHead(one, head);
head = addHead(two, head);
}
}
return head;
}
private static ListNode addHead(int value, ListNode head) {
ListNode node = new ListNode(value);
node.next = head;
if (head != null)
head.prev = node;
return node;
}
private static ListNode addTail(int value, ListNode tail) {
ListNode node = new ListNode(value);
node.prev = tail;
if (tail != null)
tail.next = node;
return node;
}
private static int getRandomValue(Random random) {
return (random.nextInt(30) + 1) * (random.nextBoolean() ? 1 : -1);
}
public static final class ListNode {
public final int value;
public ListNode next;
public ListNode prev;
public ListNode(int value) {
this.value = value;
}
#Override
public String toString() {
return String.valueOf(value);
}
}
I don't know if i got your requirements correctly. But here is a loop that would achieve a doubly linked list with your tete and queue. The comments explain the logic.
class LC {
public int data;
public LC suiv;
public LC prec;
}
public class ChainesDouble {
public static int getRandom(){
int N = (int)(Math.random()*42);
if(N<21) {
N -=30;
} else {
N-=11;
}
return N;
}
public static void main(String[] args) {
int N = (int)(Math.random()*16)+5;
N = (N*2);
System.out.println("La valeur de N = " + N);
LC tete = null;
LC queue = null;
for (int i = 0; i < N/2; i++) {
int valeur = getRandom();
int next = getRandom();
//get the two random values
LC temp_a = new LC();
LC temp_b = new LC();
//Store the data in the two nodes
temp_a.data = valeur;
temp_b.data = next ;
//link the two nodes
temp_a.suiv = temp_b;
temp_b.prec = temp_a;
//If the list is empty, then initialize tete(head) and queue(tail)
if(tete == null) {
tete = temp_a;
queue = temp_b;
} else {
if(valeur <0) { //If valeur is negative, add to tete
temp_b.suiv = tete;
tete.prec = temp_b;
tete = temp_a;
}
else { //If valeur is positive, add to queue
queue.suiv = temp_a;
temp_a.prec = queue;
queue = temp_b;
}
}
}
//Test Program
LC temp = tete;
while (temp!=null) {
System.out.println(temp.data);
temp=temp.suiv;
}
//Search for second multiple of 5
LC search = tete;
int count = 0;
boolean found = false;
while (search!=null) {
if (search.data%5==0)
count++;
if (count==2) {
found = true;
System.out.println("Found "+search.data);
break;
}
search = search.suiv;
}
//if found
if (found) {
int position = 5;
if (search.data%10==0) position = 10;
System.out.println("Position "+position);
//remove search for current position
if (search.suiv!=null) {
LC prev = search.prec;
LC next = search.suiv;
prev.suiv = next;
next.prec = prev;
} else {
search.prec.suiv = null;
}
//move pointer to desired position
LC move = tete;
int cur = 1;
while(move!=null) {
move = move.suiv;
cur++;
if (cur==(position - 1)) {
break;
}
}
System.out.println("shifting "+search.data+" to after "+move.data);
//link searched item into desired position
search.suiv = move.suiv;
move.suiv.prec = search;
move.suiv = search;
search.prec = move;
}
}
}
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?
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]
I'm working on an assignment where I need to create a Linked List given a template. For each new node that is created, I need to print out the updated list. However, up until this point, I've been stumped on how to print out the linked list. Can anyone figure out what am I doing wrong? What I currently have just prints out the number that has been created, followed by blank space, instead of the entire list up to that point.
NumberList.java
import java.util.*;
public class NumberList {
private Node head;
public NumberList() {
}
public void insertAtHead(int x) {
Node newNode = new Node(x);
if (head == null)
head = newNode;
else {
newNode.setNext(head);
head = newNode;
}
}
public void insertAtTail(int x) {
}
public void insertInOrder(int x) {
}
public String toString() {
Node tmp = head;
String result = "";
while (tmp.getNext() != null) {
result += tmp.toString() + " ";
}
return result;
}
//---------------------
// test methods
//---------------------
public static void testInsertAtHead() {
Random r = new Random();
int n = 20;
int range = 1000;
NumberList list = new NumberList();
for (int i=1; i<=n; i++) {
int x = r.nextInt(range);
list.insertAtHead(x);
System.out.println("" + x + ": " + list);
}
}
public static void testInsertAtTail() {
Random r = new Random();
int n = 20;
int range = 1000;
NumberList list = new NumberList();
for (int i=1; i<=n; i++) {
int x = r.nextInt(range);
list.insertAtTail(x);
System.out.println("" + x + ": " + list);
}
}
public static void testInsertInOrder() {
Random r = new Random();
int n = 20;
int range = 1000;
NumberList list = new NumberList();
for (int i=1; i<=n; i++) {
int x = r.nextInt(range);
list.insertInOrder(x);
System.out.println("" + x + ": " + list);
}
}
public static void main(String[] args) {
//testInsertAtHead();
//testInsertAtTail();
testInsertInOrder();
}
}
Node.java
class Node {
private int number;
private Node next;
public Node(int n) {
this.number = n;
this.next = null;
}
public Node getNext() {
return next;
}
public int getNumber() {
return number;
}
public void setNext(Node n) {
if (n == null)
return;
n.setNext(next);
next = n;
}
public String toString() {
return number + "";
}
}
I think your toString() is looping endlessly once the second element is added. You need to move your pointer to the next node:
public String toString() {
Node tmp = head;
String result = "";
while (tmp != null) {
result += tmp.toString() + " ";
tmp = tmp.getNext();
}
return result;
}
I've also updated the condition to handle a null head.