I have already put in the following methods for a binary search tree:
import java.util.Collections;
import java.util.NoSuchElementException;
import java.util.ArrayList;
public class MyTree {
private class Node
{
public String data;
public int data2;
public Node left;
public Node right;
public Node(String data, Node left, Node right)
{
this.data = data;
this.left = left;
this.right = right;
}
}
private static Node root = null;
private int getHeight(Node subroot)
{
if (subroot == null)
return -1;
int maxLeft = getHeight(subroot.left);
int maxRight = getHeight(subroot.right);
return Math.max(maxLeft, maxRight) + 1;
}
public String toString()
{
return toString(this.root);
}
private String toString(Node subroot)
{
if (subroot==null)
return "";
return toString(subroot.left)+subroot.data+toString(subroot.right);
}
public boolean containsRecursive(String value)
{
return contains(value, this.root);
}
private boolean contains(String value, Node subroot)
{
if (subroot==null)
return false;
else if (value.equals(subroot.data))
return true;
else if (value.compareTo(subroot.data) < 0)
return contains(value, subroot.left);
else
return contains(value, subroot.right);
}
public boolean contains(String value) // not recursive
{
Node subroot = this.root;
while (subroot != null)
{
if (value.equals(subroot.data))
return true;
else if (value.compareTo(subroot.data) < 0)
subroot = subroot.left;
else
subroot = subroot.right;
}
return false;
}
public int addUp()
{
return addUp(this.root);
}
private int addUp(Node subroot)
{
if (subroot==null)
return 0;
return addUp(subroot.left)+subroot.data2+addUp(subroot.right);
} //data = String, data2 = int
public int count()
{
return count(this.root);
}
private int count(Node subroot)
{
if (subroot==null)
return 0;
return count(subroot.left)+1+count(subroot.right);
}
public int numberLess(int x)
{
return numberLess(this.root, x);
}
private int numberLess(Node subroot, int x)
{
if (subroot==null)
return 0;
if (x < subroot.data2)
return numberLess(subroot.left, x)+1+numberLess(subroot.right, x);
return numberLess(subroot.left, x)+numberLess(subroot.right, x);
}
public int findMax()
{
return findMax(this.root);
}
private int findMax(Node subroot) throws NoSuchElementException
{
if (subroot==null)
throw new NoSuchElementException();
return Math.max(findMax(subroot.left), findMax(subroot.right));
}
private ArrayList<Integer> addToList(Node subroot, ArrayList<Integer> a)
{
if (subroot!=null){
a.add(subroot.data2);
addToList(subroot.left, a).addAll(addToList(subroot.right, a));
return a;
}
return new ArrayList<Integer>();
}
private ArrayList<Integer> getSortedList(){
ArrayList<Integer> rawList = addToList(this.root, new ArrayList<Integer>());
Collections.sort(rawList);
return rawList;
}
public void rebalance(){
ArrayList<Integer> list = getSortedList();
}
}
How can I finish the rebalance method using the structure I already have? I'd like to use the sorted arraylist by finding the midpoints and recursively ordering them. I'm not sure how this would be approached using the way I have my tree set up (with the internal node class) so I'd like some help with this code.
Split the array in two equal sized portions. Take the median element as new root node.
Then split again the two portions and take the median element as second level nodes, etc.
Best implemented recursively....
Related
The goal is to pass a data structure(queue) through a constructor and return a new queue once it goes through a method. I created a method of type Queue that converts from infix to postfix order. The problem is, when I pass the queue through the constructor, I am outputting all 'a's instead of the equation itself. So, I know that the linked list is passing the LENGTH of the queue, but not the characters themselves.
Output:
a+b+c/(d+f)
aaaaaaaaaaa
Main Class:
import java.io.*;
import java.lang.*;
class Convert
{
static int Prec(char ch)
{
switch (ch)
{
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
}
return -1;
}
public static QueueADT infixToPostFix(QueueADT in)
{
QueueADT infix = in;
QueueADT result = new QueueADT();
StackADT stack = new StackADT();
while(infix.empty() == false)
{
char c = infix.dequeue();
if (Character.isLetterOrDigit(c))
result.enqueue(c);
else if (c == '(')
stack.push(c);
else if (c == ')')
{
while (!stack.empty() && stack.peek() != '(')
result.enqueue(stack.pop());
stack.pop();
}
else // an operator is encountered
{
while (!stack.empty() && Prec(c) <= Prec(stack.peek()))
result.enqueue(stack.pop());
stack.push(c);
}
}
// pop all the operators from the stack
while (!stack.empty())
result.enqueue(stack.pop());
return result;
}
public static void main(String[] args)
{
QueueADT infix = new QueueADT();
String str = "a+b+c/(d+f)";
for(int i=0; i < str.length(); i++)
{
infix.enqueue(str.charAt(i));
System.out.print(str.charAt(i));
}
QueueADT postfix = infixToPostFix(infix);
System.out.println();
while(!postfix.empty())
{
System.out.print(postfix.dequeue());
}
}
}
Queue Class:
public class QueueADT
{
private int size;
private Node front;
private Node rear;
public QueueADT()
{
size = 0;
front = null;
rear = null;
}
public boolean empty()
{
return(size == 0);
}
public int size()
{
return size;
}
public void enqueue(char character)
{
Node newNode = new Node();
newNode.setData(character);
newNode.setNext(null);
if(this.empty())
{
front = newNode;
}
else
rear.setNext(newNode);
rear = newNode;
size++;
}
public char dequeue()
{
char i;
i = front.getData();
size--;
if(this.empty())
rear = null;
return i;
}
public char front()
{
return front.getData();
}
}
Stack class:
public class StackADT
{
private Node top;
private int size;
public StackADT()
{
top = null;
size = 0;
}
public boolean empty()
{
return (top == null);
}
public char peek()
{
return top.getData();
}
public int size()
{
return size;
}
public void push(char character)
{
Node newNode = new Node();
newNode.setData(character);
newNode.setNext(top);
top = newNode;
size++;
}
public char pop()
{
char i;
i = top.getData();
top = top.getNext();
size--;
return i;
}
public int onTop()
{
char i = pop();
push(i);
return i;
}
}
Node class:
public class Node
{
private char data;
private Node next;
public Node()
{
data = 0;
next = null;
}
public Node(char d)
{
data = d;
}
public Node(char d, Node n)
{
data = d;
next = n;
}
public void setData(char newData)
{
data = newData;
}
public void setNext(Node newNext)
{
next = newNext;
}
public char getData()
{
return data;
}
public Node getNext()
{
return next;
}
public void displayNode()
{
System.out.print(data);
}
}
Your implementation of dequeue method in QueueADT class is incorrect. You never change field "front", that's why when you call that method in your case, 'a' is always being returned. Add
front = front.getNext();
after line
char i = front.getData();
There are more problems with that code - try testing each of your methods separately, not only the program as a whole.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I have scoured the internet and cannot find the answer to my question. I am currently in a data structures course, which is important to this question because I need to make EVERYTHING from scratch. I am currently working on homework and the question is this:
Using a USet, implement a Bag. A Bag is like a USet—it supports the add(x), remove(x), and find(x) methods—but it allows duplicate elements to be stored. The find(x) operation in a Bag returns some element (if any) that is equal to x. In addition, a Bag supports the findAll(x) operation that returns a list of all elements in the Bag that are equal to x.
I have done almost all of it and now when I am trying to test my code it throws a null pointer exception right off the bat. I went through the debugger and although I know where it is failing (when trying to create my array list and fill it with linked lists) I just dont know how to fix it. Here is what the error states:
Exception in thread "main" java.lang.NullPointerException
at Bag.<init>(Bag.java:10)
at Bag.main(Bag.java:198)
because I havent even gotten it to start I obviously dont know of any other errors it will encounter, but I will face those when this is fixed. I appreciate any help.
Reminder: I cannot use pre-built java dictionaries, everything needs to be done from the basics.
Here is my entire code:
public class Bag<T> {
final int ARR_SIZE = 128;
LinkedList[] theArray;
public Bag() {
for (int i = 0; i < ARR_SIZE; i++) {
theArray[i] = new LinkedList();
}
}
public boolean add(T x) {
T element = x;
int hashKey = element.hashCode() % ARR_SIZE;
theArray[hashKey].addFirst(element, hashKey);
return true;
}
public T find(T x) {
T element = x;
int hashKey = element.hashCode() % ARR_SIZE;
return theArray[hashKey].findNode(element).getData();
}
public T findAll(T x) {
T element = x;
int hashKey = element.hashCode() % ARR_SIZE;
System.out.print(theArray[hashKey].findAllElements(element));
return element;
}
public T remove(T x) {
T element = x;
int hashKey = element.hashCode() % ARR_SIZE;
return theArray[hashKey].removeElement(element);
}
public int size() {
return ARR_SIZE;
}
public class Node {
T data;
int key;
Node next;
Node prev;
public Node(T t, int k, Node p, Node n) {
data = t;
key = k;
prev = p;
next = n;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public Node getPrev() {
return prev;
}
public void setPrev(Node prev) {
this.prev = prev;
}
public void display() {
System.out.println(data);
}
}
public class LinkedList {
Node header;
Node trailer;
int size = 0;
public LinkedList() {
header = new Node(null, -1, trailer, null);
trailer = new Node(null, -1, null, null);
header.setNext(trailer);
}
public int size() {
return size;
}
public boolean isEmpty() {
return size() == 0;
}
public void addFirst(T t, int hashKey) {
Node currentLast = header.getNext();
Node newest = new Node(t, hashKey, header, currentLast);
header.setNext(newest);
currentLast.setPrev(newest);
size++;
}
public T add(T t) {
Node currentLast = header.getNext();
Node newest = new Node(t, -1, header, currentLast);
header.setNext(newest);
currentLast.setPrev(newest);
size++;
return newest.getData();
}
public T removeElement(T t) {
if (isEmpty()) {
return null;
}
T element = t;
return removeNode(findNode(element));
}
public T removeNode(Node node) {
if (isEmpty()) {
return null;
}
Node pred = node.getPrev();
Node succ = node.getNext();
pred.setNext(succ);
succ.setPrev(pred);
size--;
return node.getData();
}
public LinkedList findAllElements(T t) {
Node current = header.getNext();
T element = t;
if (isEmpty()) {
return null;
}
LinkedList all = new LinkedList();
while (current != null) {
if (current.getData() == element) {
all.addFirst(element, -1);
} else {
current = current.getNext();
}
}
return all;
}
public Node findNode(T t) {
Node current = header.getNext();
T element = t;
if (isEmpty()) {
return null;
}
while (current.getNext() != null && current.getData() != element) {
current = current.getNext();
}
if (current.getNext() == null && current.getData() != element) {
System.out.println("Does not exist");
}
return current;
}
}
public static void main(String[] args) {
Bag<Integer> bag = new Bag();
bag.add(1);
bag.add(1);
bag.add(2);
bag.add(2);
bag.add(8);
bag.add(5);
bag.add(90);
bag.add(43);
bag.add(43);
bag.add(77);
bag.add(100);
bag.add(88);
bag.add(555);
bag.add(345);
bag.add(555);
bag.add(999);
bag.find(1);
}
}
Initialize your theArray to avoid NullPointerExceptions.
LinkedList[] theArray = new LinkedList[ARR_SIZE];
I have a superclass called Tree and a subclass called AVLTree that extends the class Tree.
A tree has children that are also Tree typed. An AVLTree has children that are AVLTree. I want to use the methods i wrote on the Tree class, on this case the getLeft(returns the left son) and setLeft(set the left son).
The problem is the compiler can't convert a Tree to an AVLTree, even though they have the same variables, structure and constructors.
Any ideas on how should I solve this? Or should I just write all the methods that just an AVLTree has on the Tree class?
The code:
Tree.java:
public class Tree<T extends Tree<T>> {
private T left = null;
private T right = null;
private Object data = null;
public Tree () {
//nothing
}
public Tree (Object data, T left, T right) {
this.data = data;
this.left = left;
this.right = right;
}
public Tree (Object data) {
this.data = data;
}
//Get Values
public T getLeft() {
return this.left;
}
public T getRight() {
return this.right;
}
public Object getData() {
return this.data;
}
//Set Values
public void setLeft(T left) {
this.left = left;
}
public void setRight(T right) {
this.right = right;
}
public void setData(Object data) {
this.data = data;
}
public T treeFromText(String in) {
if (in=="()") return null;
int i=0;
T result = null;
//Find expression
int d = in.indexOf('c')+1;
if (d==0) return null;
int begl, endl, begr, endr;
begl = d+1;
endl = ClosingParentesis(in,begl);
endr = in.length()-2;
begr = OpeningParentesis(in,endr);
T left = null, right = null;
if (begl-endl==0) {
left = null;
} else left = treeFromText(in.substring(begl,endl+1));
if (begr-endr==0) {
right = null;
} else right = treeFromText(in.substring(begr,endr+1));
result.setData(in.charAt(d));
result.setLeft(left);
result.setRight(right);
return result;
}
public static int ClosingParentesis(String in, int openPos) {
int closePos = openPos;
int counter = 1;
while (counter > 0 && closePos < in.length()-1) {
closePos++;
if (in.charAt(closePos)=='(') counter++;
if (in.charAt(closePos)==')') counter--;
}
return closePos;
}
public static int OpeningParentesis(String in, int closePos) {
int openPos = closePos;
int counter = 1;
while (counter > 0 && openPos > 0) {
openPos--;
if (in.charAt(openPos)=='(') counter--;
if (in.charAt(openPos)==')') counter++;
}
return openPos;
}
AVLTree.java:
public class AVLTree extends Tree<AVLTree> {
/*
//Values and Variables
private AVLTree left = null;
private AVLTree right = null;
private Object data;
//Inicialization
public AVLTree (Object data, AVLTree left, AVLTree right) {
super(data,left,right);
}
public AVLTree (Object data) {
super(data);
}
*/
public int getfactor() {
return getHeight(this.getLeft())-getHeight(this.getRight());
}
}
Test.java:
public static void main(String[] args) {
AVLTree tree = new AVLTree();
Scanner console = new Scanner(System.in);
String in = console.nextLine().toLowerCase();
tree = (AVLTree) tree.treeFromText(in); //The error is here.
System.out.println(tree.getHeight());
System.out.println(tree.TreePreOrder());
}
The way I expect it to work is that if the String 'in' in the Test.java is "(c3()(c2()()))" the return must be an Tree with value 3 and a right son with value 2. This return must be of type Tree or anything that extends Tree.
You need a way to get an AVLTree instantiated from a String, using the logic in Tree.treeFromText.
Declare Tree as abstract.
Create a new method in Tree:
abstract protected T createEmptyTree();
Override that method in AVLTree to return an empty instance of AVLTree.
#Override
protected AVLTree createEmptyTree() {
return new AVLTree();
}
In treeFromText(), wherever you need to create an empty instance of T, invoke createEmptyTree().
You already have the rest of the logic.
Try to avoid returning null anywhere. It's best to return an empty AVLTree instead of a null.
You can achieve this by the power of generics: define a new circular generic T:
public class Tree<T extends Tree<T>>
{
T left;
T right;
public T doSomething()
{
return left;
}
public static class AVLTree extends Tree<AVLTree>
{
public AVLTree foo()
{
return doSomething();
}
}
}
UPDATE: here is how you can create different tree instances:
import java.util.Objects;
public class TreesFactory
{
public static AVLTree createAVLTreeFrom(String in)
{
return treeFromText(in, AVLTree::new);
}
#FunctionalInterface
interface SimpleFactory<T extends Tree<T>>
{
T createNew();
}
public static <T extends Tree<T>> T treeFromText(String in, SimpleFactory<T> treeFactory)
{
if (Objects.equals(in, "()"))
return null;
T result = treeFactory.createNew();
//Find expression
int d = in.indexOf('c') + 1;
if (d == 0)
return null;
int begl, endl, begr, endr;
begl = d + 1;
endl = ClosingParentesis(in, begl);
endr = in.length() - 2;
begr = OpeningParentesis(in, endr);
T left, right;
if (begl - endl == 0)
{
left = null;
}
else
left = treeFromText(in.substring(begl, endl + 1), treeFactory);
if (begr - endr == 0)
{
right = null;
}
else
right = treeFromText(in.substring(begr, endr + 1), treeFactory);
result.setData(in.charAt(d));
result.setLeft(left);
result.setRight(right);
return result;
}
public static int ClosingParentesis(String in, int openPos)
{
int closePos = openPos;
int counter = 1;
while (counter > 0 && closePos < in.length() - 1)
{
closePos++;
if (in.charAt(closePos) == '(')
counter++;
if (in.charAt(closePos) == ')')
counter--;
}
return closePos;
}
public static int OpeningParentesis(String in, int closePos)
{
int openPos = closePos;
int counter = 1;
while (counter > 0 && openPos > 0)
{
openPos--;
if (in.charAt(openPos) == '(')
counter--;
if (in.charAt(openPos) == ')')
counter++;
}
return openPos;
}
}
And the Main:
public static void main(String[] args)
{
Scanner console = new Scanner(System.in);
String in = console.nextLine().toLowerCase();
AVLTree tree = TreesFactory.createAVLTreeFrom(in);
//...
}
I'm working on a school assignment about creating a balanced binary tree. Interfaces for the Node and the Tree were supplied with declared methods. However, the Node interface had only getLeft, getRight and getValue methods, no setters. Since we submit for grading only the implementation files, I worked around it by using the implementation class itself for typing, instead of the Interface.
When I messaged the teacher, he told me it was possible to implement it using merely the Node constructor, adding a "hint" that "For every node, its child are also trees." which is obvious, but I'm not sure how that is to help me.
It seems to me that without using setters, I'd first need to basically map out the tree in advance and then start building it from bottom instead of from top, which seems needlessly complicated and counter-intuitive. Is there some trick I'm missing?
Thank you for any help or advice you can offer.
My current implementations are as follows:
TreeImpl.java
public class TreeImpl implements Tree {
private NodeImpl root;
public TreeImpl() {}
#Override
public void setTree(int[] values) {
this.root = null;
Arrays.sort(values);
recurseSet(values);
}
private void recurseSet(int[] values) {
if (values.length > 0) {
int middleIndex = values.length / 2;
NodeImpl tempNode = new NodeImpl(values[middleIndex]);
insert(tempNode, root, 1);
recurseSet(cutArray(values, 0, middleIndex - 1));
recurseSet(cutArray(values, middleIndex+1, values.length-1));
}
}
private int[] cutArray(int[] array, int begin, int end) {
int length = end-begin+1;
int[] newArray = new int[length];
System.arraycopy(array, begin, newArray, 0, length);
return newArray;
}
private void insert(NodeImpl node, NodeImpl location, int depth) {
if (root == null) {
root = node;
return;
}
if (node.getValue() < location.getValue()) {
/* left branch */
if(location.getLeft() == null) {
node.setDepth(depth);
location.setLeft(node);
} else {
insert(node, location.getLeft(), depth+1);
}
} else {
/* right branch */
if(location.getRight() == null) {
node.setDepth(depth);
location.setRight(node);
} else {
insert(node, location.getRight(), depth+1);
}
}
}
#Override
public Node getRoot() {
return root;
}
private String toString(NodeImpl root) {
String finalString = "";
if (root != null) {
finalString += root;
finalString += toString(root.getLeft());
finalString += toString(root.getRight());
}
return finalString;
}
#Override
public String toString() {
return toString(root);
}
}
NodeImpl.java
public class NodeImpl implements Node {
private int value;
private NodeImpl left;
private NodeImpl right;
private int depth = 0;
public NodeImpl(int value) {
this.value = value;
}
public void setLeft(NodeImpl left) {
this.left = left;
}
public void setRight(NodeImpl right) {
this.right = right;
}
public void setDepth(int depth) {
this.depth = depth;
}
#Override
public NodeImpl getLeft() {
return left;
}
#Override
public NodeImpl getRight() {
return right;
}
#Override
public int getValue() {
try {
return value;
} catch (NullPointerException e) {
System.out.println("Null pointer.");
}
return 0;
}
#Override
public String toString() {
String finalString = "";
for(int i = 0; i < depth; i++) {
finalString += " ";
}
finalString += "- ";
finalString += value;
finalString += "\n";
return finalString;
}
}
I played with your code a little bit and I think I've figured out how to do that:
class NodeImpl implements Node {
private int value;
private Node left;
private Node right;
public NodeImpl(int value, Node left, Node right) {
this.value = value;
this.left = left;
this.right = right;
}
public Node getLeft() {
return left;
}
public Node getRight() {
return right;
}
public int getValue() {
return value;
}
#Override
public String toString() {
// here you have to put some nice drawing logic.
return (left != null ? left.toString() : "") + "<-" + value + "->" + (right != null ? right.toString() : "");
}
}
class TreeImpl implements Tree {
private Node root;
public void setTree(int[] values) {
Arrays.sort(values);
this.root = recurseSet(values);
}
private Node recurseSet(int[] values) {
if (values.length > 0) {
int middleIndex = values.length / 2;
return new NodeImpl(
values[middleIndex], recurseSet(cutArray(values, 0, middleIndex - 1)),
recurseSet(cutArray(values, middleIndex + 1, values.length - 1))
);
} else {
return null;
}
}
private int[] cutArray(int[] array, int begin, int end) {
int length = end - begin + 1;
int[] newArray = new int[length];
System.arraycopy(array, begin, newArray, 0, length);
return newArray;
}
public Node getRoot() {
return root;
}
}
And you will use your classes like:
public static void main(String[] args) {
final Tree tree = new TreeImpl();
tree.setTree(new int[]{1, 10, 9, 8, 2, 5});
System.out.println(tree.getRoot().toString());
}
You just have to think how to implement NodeImpl.toString() method to draw each node in a nice way :) I hope it will help you.
I'm having a problem with trying the logic and trying to write a min and additionMerge function and their recursive versions of the function that takes at least one list as an argument (the first node of the list). This will be a private helper function that is called by a wrapper function that is a member function of the LinkedList class.
public class LinkedList {
private static class ListNode {
public int firstItem;
public ListNode restOfList;
}
private ListNode first;
/**
* Create an empty list.
*/
public LinkedList() {
first = null;
}
public LinkedList(int n) {
first = countDown(n);
}
public LinkedList(String s) {
String[] temp = s.split(",");
for (int i = temp.length-1; i >= 0; i--) {
first = insertAtFront(first, Integer.parseInt(temp[i]));
}
}
public int length() {
return length(first);
}
private static int length(ListNode list) {
if (list == null) {
return 0;
}
int temp = length(list.restOfList);
return temp + 1;
}
public boolean contains(int value) {
return contains(first, value);
}
private static boolean contains(ListNode list, int value) {
if (list == null) {
return false;
}
if (list.firstItem == value) {
return true;
}
return contains(list.restOfList, value);
}
public int sum() {
return sum(first);
}
private static int sum(ListNode list) {
if (list == null) {
return 0;
}
return sum(list.restOfList) + list.firstItem;
}
public int count(int target) {
return count(first, target);
}
private static int count(ListNode list, int target) {
if (list == null) {
return 0;
}
int temp = count(list.restOfList, target);
if (list.firstItem == target) {
temp++;
}
return temp;
}
public void replace(int oldValue, int newValue) {
replace(first, oldValue, newValue);
}
private static void replace(ListNode list, int oldValue, int newValue) {
if (list == null) {
return;
}
replace(list.restOfList, oldValue, newValue);
if (list.firstItem == oldValue) {
list.firstItem = newValue;
}
}
public void insertAtFront(int n) {
first = insertAtFront(first, n);
}
private static ListNode insertAtFront(ListNode list, int n) {
ListNode answer = new ListNode();
answer.firstItem = n;
answer.restOfList = list;
return answer;
}
private static ListNode countDown(int n) {
if (n == 1) {
ListNode answer = new ListNode();
answer.firstItem = 1;
answer.restOfList = null;
return answer;
}
ListNode temp = countDown(n - 1);
ListNode answer = insertAtFront(temp, n);
return answer;
}
public void insertAtBack(int item) {
first = insertAtBack(first, item);
}
private static ListNode insertAtBack(ListNode list, int item) {
if (list == null) {
ListNode answer = new ListNode();
answer.firstItem = item;
answer.restOfList = null;
return answer;
}
//List answer = new ListNode();
//answer.firstItem = list.firstItem;
ListNode temp = insertAtBack(list.restOfList, item);
//answer.restOfList = temp;
list.restOfList = temp;
return list;
}
public void concatenate(LinkedList otherList) {
this.first = concatenate(this.first, otherList.first);
}
private static ListNode concatenate(ListNode list1, ListNode list2) {
if (list1 == null) {
return list2;
}
ListNode temp = concatenate(list1.restOfList, list2);
list1.restOfList = temp;
return list1;
}
public void filter(int item) {
first = filter(first, item);
}
#Override
public String toString() {
if (first == null) {
return "";
}
StringBuilder sb = new StringBuilder(256);
sb.append(first.firstItem);
for (ListNode current = first.restOfList;
current != null;
current = current.restOfList) {
sb.append(',');
sb.append(current.firstItem);
}
return sb.toString();
}
private static ListNode filter(ListNode list, int item) {
if (list == null) {
return null;
}
ListNode temp = filter(list.restOfList, item);
if (list.firstItem == item) {
return temp;
}
list.restOfList = temp;
return list;
}
public int min() throws RuntimeException {
if (first == null)
throw new RuntimeException("List is Empty");
else
return min();
}
// * A private recursive helper function that returns the minimum item in a
* list whose first node is the argument list.
private static int min(ListNode list) throws RuntimeException {
if (list == null) {
return 0;
}
}
public void additionMerge(LinkedList l2) {
}
* Every node in the list that begins with node
* node1 is increased by the ammount of the corresponding
* node in the list that begins with node node2.
* If one list is longer than the other, the missing nodes
* in the shorter list are assumed to be 0.
private static ListNode additionMerge(ListNode node1, ListNode node2) {
if (list == null) {
return null;
}
}
}
If this is not homework, then my advice is:
Don't write your own LinkedList class. Use the existing out, and add the extra functionality either as a helper class or by extending the existing class.
If you do decide to implement your own linked list class, then you should beware of using recursion. Recursion gives a neat soltion, but there is a major drawback with recursion in Java. The JVM does not do tail call optimization, so a recusive algorithm that recurses deeply (e.g. recursively traversing a long list) is liable to cause a StackOverflowError.