Displaying a linked list in java - java

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.

Related

How to delete a node in a circular doubly linked list?

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.

How to Instantiate Connection between Student Class and my LinkedList<E>. Wont grab E.getElement()

I'm working on creating my own LinkedList. My L.L. worked 100% when running simple I/O from command line, but now I have to implement it into my Student class. It adds a Student, displays a student, won't remove Student # Node, in-fact, it won't even read THE ONLY student in the list! All BlueJ tells me is this:
Error(s) found in class
It's some kind of connection logic and for two days I have tried everything I can think of.
Here is my Student, removeStudent(), Class Node, and LinkedList
public class Node
{
private Student item;
private Node node;
private int thisIdx;
private String fullName,firstName,lastName,gender,major,netId;
private int uin,age;
private double gpa;
public Node()
{
this(null,null);
}
public Node(Student stu,Node node)
{
this.item = stu;
this.setNext(node);
thisIdx = totalCount() - 1;
this.setNodeIndex(thisIdx);
}
public int getIndex()
{
return this.thisIdx;
}
public void setNodeIndex(int idx)
{
thisIdx = idx;
}
public void setNext(Node n1)
{
node = n1;
}
public Node getNext()
{
return node;
}
public boolean isEmpty()
{
return ( this == null);
}
public Student display()
{
return this.item;
}
public void setItem(Links data)
{
this.item = data;
}
public Student getItem()
{
return item;
}
}
public class Links<E>
{
private Node start,tail,next;
private int size=0; private int idx; private String item;
private Student student;
/**
* Constructor for objects of class MyLList
*/
public Links()
{
start = new Node();
}
public void addLink(E object)
{
tail = start;
start = new Node(object,tail);
size++;
}
public int totalCount()
{
return size;
}
public Node get(Node node)
{
return node;
}
public void set(Node node)
{
node.setNext(node.getNext());
}
public String emptyMessage()
{
String message = "Your student is not in the student files.\n\n";
return message;
}
public Node getStart()
{
Node curr = start;
return curr;
}
public void clear()
{
Node start = new Node();
size = 0;
}
public void removeLink(Node node) throws NullPointerException
{
try{
Node del,curr,next,prev;
prev = start; curr = start;
while ( curr != node )
{
if ( curr.getNext() == null)
{
throw new NullPointerException();
}else
{
prev = curr;
curr = curr.getNext();
}
}
if ( curr == start)
{
start = start.getNext();
}else
{
prev.setNext(curr.getNext());
curr = curr.getNext();
}
}catch (NullPointerException npe)
{
Lab_12.viewer.append("Breaking in Links" + "\n\n");
}
}
public void sort()
{
Node curr,next,temp,prev;
prev = start;
curr = start;
next = start.getNext();
int move;
Student[] copyToThis = new Student[this.size];
if (this.totalCount() > 1)
{
//copy contents of linked list to array
for (int i=0; i < this.totalCount(); i++)
{
if ( !curr.isEmpty() )
{
Student copyItem = curr.getItem();
copyToThis[i] = copyItem;
prev = curr;
if ( curr.getNext() != null)
{
curr = curr.getNext();
}else
{
prev.setNext(curr.getNext());
}
}
for (int k=0; k < copyToThis.length-1;k++)
{
int tempIdx = k;
if ( copyToThis[k] == null )
{
copyToThis[tempIdx] = copyToThis[k];
while ( k < copyToThis.length-1 )
{
copyToThis[k] = copyToThis[k+1];
copyToThis[k+1] = copyToThis[tempIdx];
tempIdx = k;
k++;
}
}
}
}
//sort array in reverse order -----> LinkedList is FIFO structure
for (int i =0; i < copyToThis.length; i++)
{
Student first = copyToThis[i];
Student tempObject = copyToThis[i];
int tempIndex = i;
for (int k=i; k < copyToThis.length; k++)
{
if (copyToThis[k] != null)
{
move = copyToThis[k].getFullName().compareToIgnoreCase(first.getFullName());
if (move > 0)
{
first = copyToThis[k];
tempIndex = k;
}
}else
{
break;
}
}
if (first == null )
{
break;
}else
{
move = first.getFullName().compareToIgnoreCase(tempObject.getFullName());
if (move > 0 )
{
copyToThis[i] = first;
copyToThis[tempIndex] = tempObject;
tempIndex = i;
}
}
}
//clear list before setting in alphabetical order -----> if not cleared, list will append not replace
this.clear();
for (int i=0; i < copyToThis.length; i++)
{
if ( copyToThis[i] != null)
{
this.addLink(copyToThis[i]);
}
}
}
//test print of array
/*for (int i=0; i < copyToThis.length; i++)
{
Lab_12.viewer.append(i + ") " + copyToThis[i]);
}*/
}
public String displayFirst()
{
Node first = start;
String showFirst = first.getItem().toString();
return showFirst;
}
public void display()
{
String showThisView;
Node prev,curr,next;
prev = start; curr = prev; next = start.getNext();
for (int i=0; i < this.totalCount();i++)
{
if (!curr.isEmpty())
{
showThisView = curr.getItem().toString();
Lab_12.viewer.append(showThisView + "\n\n");
}else
{
prev.setNext(curr.getNext());
curr = curr.getNext();
next = next.getNext();
}
prev = next;
curr = prev;
if (prev.getNext() != null)
{
next = prev.getNext();
}else
{
break;
}
}
}
public String search(String data) throws NullPointerException
{
try{
Node p = start;
while(p!=null)
{
if ( !p.getItem().equals(data) )
{
p = p.getNext();
}else
{
return data;
}
}
}catch (NullPointerException npe)
{
System.out.println("Your item is not in the list\n");
}
}
}
public void removeStudent(Links<Student> studentLinks1)
{
try
{
String toRemove;
int choice;
int counter =0;
toRemove = JOptionPane.showInputDialog(null,"Enter the student last name to be removed:");
String find;
int uin;
for (Node i=studentLinks1.getStart(); i.getNext() != null; i.setNext(i.getNext()) )
{
if ( studentLinks1.get(i).getFullName().equalsIgnoreCase(toRemove) )
{
counter++;
}
}
if (counter > 1)
{
viewer.append("You have more than one student with the last name, " + toRemove + ".\n\n");
viewer.append("Students with last name: " + toRemove + "\n\n");
/*
* create array to hold current matching indexes;
*/
for (Node i=studentLinks1.getStart(); i.getNext() !=null; i.setNext(i.getNext()))
{
find = studentLinks1.get(i).getLastName().toString();
if ( studentLinks1.get(i).getLastName().equalsIgnoreCase(toRemove) )
{
uin = studentLinks1.get(i).getUin();
viewer.append("Name: " + studentLinks1.get(i).getFullName().toString() +
"\n\tUIN: " + uin + "\n\n");
}
}
/*
* Get user input for student removal & remove student
*/
int match = 0;
choice = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter the UIN of the student you wish to remove: "));
for (Node i=studentLinks1.getStart(); i.getNext() !=null ; i.setNext(i.getNext()))
{
uin = studentLinks1.get(i).getUin();
if ( choice != uin)
{
match++;
}
if (match == Links.totalCount() )
{
throw new InputMismatchException();
}
}
for (Node i=studentLinks1.getStart(); i.getNext() != null; i.setNext(i.getNext()))
{
if ( studentLinks1.get(i).getUin() == choice )
{
String name = studentLinks1.get(i).getFullName().toString();
viewer.append(name + " " + " has been removed from the student file." + "\n\n");
studentLinks1.removeLink(i);
Student.removeStudent();
Student.getStudentCount();
}
}
viewer.append("There is " + Student.getStudentCount() + " student(s) in your student file." + "\n\n");
if ( counter == 1)
{
for (Node i=studentLinks1.getStart(); i.getNext() != null; i.setNext(i.getNext()))
{
if ( studentLinks1.get(i) != null && studentLinks1.get(i).getLastName().equalsIgnoreCase(toRemove) )
{
String firstName = studentLinks1.get(i).getFirstName().toString();
String lastName = studentLinks1.get(i).getLastName().toString();
viewer.append(firstName + " " + lastName + " has been removed from the student file." + "\n\n");
studentLinks1.removeLink(i);
Student.removeStudent();
}
}
viewer.append("There is " + Student.getStudentCount() + " student(s) in your student file." + "\n\n");
}else
{
viewer.append(studentLinks1.emptyMessage());
}
}
}catch (InputMismatchException ime )
{
viewer.append("You entered an incorrect student id.\nPlease re-enter the student id.");
throw ime;
}
}
As you can see in my removeStudent(), I have formatted the for loops to iterate through the L.L. with the nodes themselves. If in LL class, I can perform node.getElement() with results, then why will that not work in my main in Student? I have tried
studentLinks1.get(I).getItem().getElement();
studentLinks1.get(i.getElement())
I am seriously at a loss with this one. Any help is much appreciated!

Sorting a linked list of names alphabetically

Hey guys I am trying to sort a linked list alphabetically by multiplying the first 3 letters together. The way it works is that the first letter would take 26^2, the second letter would be 26^1 and the third would be 26^0. When i run the program it is giving me the same sum for say the name "lala" and "francis". If anybody could help me see what is wrong with the code, it will be greatly appreciated!
LinkedListNode class: (contains the getSum method)
public class LinkedListNode
{
public String data;
public LinkedListNode next;
public long sum;
public LinkedListNode(String data)
{
this.data = data;
this.next = null;
this.sum = getSum(data);
}//end node
public long getSum(String line)
{
int i;
long sum = 0;
String s = null;
char a;
for(i=0; i < 3; i++)
{
int j = 2;
a = line.charAt(i);
sum += Character.getNumericValue(a) * Math.pow(26, j);
//Return the value of the number 4 to be the power of 3 (4*4*4): Math.pow(4,3);
j--;
}//end for
return sum;
}//end getSum
public long getSum()
{
return sum;
}//end getSum
public String getData()
{
return data;
}//end getData
public void setData(String data)
{
this.data = data;
}//end setData
public LinkedListNode getNext()
{
return next;
}//end node
public void setNext(LinkedListNode next)
{
this.next = next;
}//end setNext
}//end class node
LinkedList class: (has other methods for the list)
public class LinkedList {
public LinkedListNode front;
public LinkedList() {
this.front = null;
}
public void insertBack(String data)
{
if(front == null){
front = new LinkedListNode(data);
}else{
LinkedListNode newNode = new LinkedListNode(data);
LinkedListNode current = front;
while(current.getNext() != null){
current = current.getNext();
}
current.setNext(newNode);
}
}//end insertBack
public void addAfter(LinkedListNode spot, String data)
{
LinkedListNode newNode;
newNode = new LinkedListNode(data);
newNode.next = spot.next;
spot.next = newNode;
}//end addAfter
public void addBefore(LinkedListNode spot, String data)
{
}//end addBefore
public void deleteAfter(LinkedListNode spot)
{
LinkedListNode nextNode;
nextNode = spot.next;
spot.next = nextNode.next;
}//end deleteAfter
public String showList()
{
int i = 0;
String retStr = "The nodes in the list are:\n";
LinkedListNode current = front;
while(current != null){
i++;
retStr += "Node " + i + " is: " + current.getData() + " and the sum is: " + current.getSum() + "\n";
current = current.getNext();
}
return retStr;
}
public LinkedListNode findTail()
{
LinkedListNode current = front;
while(current.getNext() != null)
{
current = current.getNext();
}
return current;
}//end findTail
}
fileIn class:
import java.util.Scanner;
import java.io.*;
public class fileIn
{
LinkedListNode front;
LinkedList myList = new LinkedList();
String fname;
public static void main(String[] args)
{
fileIn f = new fileIn();
}//end main
public fileIn()
{
getFileName();
readFileContents();
System.out.print(myList.showList());
}//end namesLinkedList
public void readFileContents()
{
boolean looping;
DataInputStream in;
String line;
int j, len;
char ch;
/* Read input from file and process. */
try
{
in = new DataInputStream(new FileInputStream(fname));
looping = true;
while(looping)
{
/* Get a line of input from the file. */
if (null == (line = in.readLine()))
{
looping = false;
/* Close and free up system resource. */
in.close();
}//end if
else
{
myList.insertBack(line);
j = 0;
len = line.length();
}//end else
} /* End while. */
} /* End try. */
catch(IOException e)
{
System.out.println("Error " + e);
} /* End catch. */
}//end readFileContents
public void getFileName()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter file name please.");
fname = in.nextLine();
}//end getFileName
}//end class namesLinkedList
for (i = 0; i < 3; i++) {
int j = 2;
a = line.charAt(i);
sum += Character.getNumericValue(a) * Math.pow(26, j);
j--;
}
You're getting the same result because the exponent is always 2. This leads to the same value for fra (15×262 + 27×262 + 10×262 = 35,152) and lal (21×262 + 10×262 + 21×262 = 35,152). Why is this?
The variable j is declared inside the loop instead of outside. The decrement at the end has no effect since it starts over at 2 at the beginning of each iteration.
You should move the declaration out of the loop:
int j = 2;
for (i = 0; i < 3; i++) {
a = line.charAt(i);
sum += Character.getNumericValue(a) * Math.pow(26, j);
j--;
}
Or you could replace j with 2 - i and get rid of the extra variable entirely.
for (i = 0; i < 3; i++) {
a = line.charAt(i);
sum += Character.getNumericValue(a) * Math.pow(26, 2 - i);
}
Looks like your math is wrong. Character.getNumericValue(a) will not return you a value between 0 and 25 like you seem to think.
Just make a custom Comparator class if you want to sort based on fist 3 letters and use that.
Edit: I was wrong about how getNumericValue works, but the math is still wrong (see comment below).

How to implement Karger's min cut algorithm in Java?

I am trying to implement Karger's min cut algorithm but I am unable to get the correct answer. Can someone please have a look at my code and help me figure out what I am doing wrong? Would really appreciate the help.
package a3;
import java.util.*;
import java.io.*;
public class Graph {
private ArrayList<Integer>[] adjList;
private int numOfVertices = 0;
private int numOfEdges = 0;
public Graph(String file) throws IOException {
FileInputStream wordsFile = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(wordsFile));
adjList = (ArrayList<Integer>[]) new ArrayList[201];
for (int i = 1; i < 201; i++) {
adjList[i] = new ArrayList<Integer>();
}
while (true) {
String s = br.readLine();
if (s == null)
break;
String[] tokens = s.split("\t");
int vertex = Integer.parseInt(tokens[0]);
this.numOfVertices++;
for (int i = 1; i < tokens.length; i++) {
Integer edge = Integer.parseInt(tokens[i]);
addEdge(vertex, edge);
this.numOfEdges++;
}
}
}
public void addEdge(int v, int w) {
adjList[v].add(w);
//this.numOfEdges++;
}
public ArrayList<Integer> getNeighbors(Integer v) {
return adjList[v];
}
public boolean hasEdge(Integer i, Integer j) {
return adjList[i].contains(j);
}
public boolean removeEdge(Integer i, Integer j) {
if (hasEdge(i, j)) {
adjList[i].remove(j);
adjList[j].remove(i);
this.numOfEdges -= 2;
return true;
}
return false;
}
public int getRandomVertex(){
Random rand = new Random();
return (rand.nextInt(this.getNumOfVertices()) + 1);
}
//Returns an array which consists of vertices connected by chosen edge
public int[] getRandomEdge(){
int arr[] = new int[2];
arr[0] = this.getRandomVertex();
while (adjList[arr[0]].size() == 0) {
arr[0] = this.getRandomVertex();
}
Random rand = new Random();
arr[1] = adjList[arr[0]].get(rand.nextInt(adjList[arr[0]].size()));
return arr;
}
//Algorithm for min cut
public int minCut() {
while (this.getNumOfVertices() > 2) {
int[] edge = this.getRandomEdge();
this.removeEdge(edge[0], edge[1]);
//Adding edges of second vertex to first vertex
for (Integer v: adjList[edge[1]]) {
if (!adjList[edge[0]].contains(v)) {
addEdge(edge[0], v);
}
}
//Removing edges of second vertex
for (Iterator<Integer> it = adjList[edge[1]].iterator(); it.hasNext();) {
Integer v = it.next();
it.remove();
this.numOfEdges--;
}
//Removing self-loops
for (Iterator<Integer> it = adjList[edge[0]].iterator(); it.hasNext();) {
Integer v = it.next();
if (v == edge[0])
it.remove();
//this.numOfEdges--;
}
this.numOfVertices--;
}
return this.numOfEdges;
}
public int getNumOfVertices() {
return this.numOfVertices;
}
public int getNumOfEdges() {
return (this.numOfEdges) / 2;
}
public String toString() {
String s = "";
for (int v = 1; v < 201; v++) {
s += v + ": ";
for (int e : adjList[v]) {
s += e + "-> ";
}
s += null + "\n";
//s += "\n";
}
return s;
}
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
int min = 1000;
//Graph test = new Graph("C:\\Users\\UE\\Desktop\\kargerMinCut.txt");
for (int i = 0; i < 10; i++) {
Graph test = new Graph("C:\\Users\\UE\\Desktop\\kargerMinCut.txt");
int currMin = test.minCut();
min = Math.min( min, currMin );
}
System.out.println(min);
}
}

Multiplying polynomials using a node class [closed]

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;

Categories

Resources