I'm creating a method to add nodes into the list. The method will have the value and the position where the user wants the node. I'm able to add the node anywhere but the start of the list.
I have also added the toString method so there is an idea of how the it is to be displayed. At the bottom I added what main has.
//ADD A NODE
public boolean add(double val, int pos)
{
Node t = root;
Node n = new Node();
int count = 1;
if(pos-1 == 0)
{
n.next = t;
t = n;
n.val = val;
}
else
while(t != null)
{
if(pos-1 == count)
{
n.next = t.next;
t.next = n;
n.val = val;
}
t = t.next;
count++;
}
return true;
}
//toString Method
public String toString()
{
String s = "Contents of list: \n";
if( root == null )
s = s + "\tThe list is empty!";
Node t = root;
while(t != null)
{
s = s + t.val + "\t";
t = t.next;
}
return s;
}
//Main
//Add Node to list
list.add(105.0, 1);
System.out.println( list );
if(pos-1 == 0)
{
n.next = t;
root = n;
n.val = val;
}
Fix this so that root is modified.
Related
public class doubleLinkedList {
class Node {
String value;
Node prev;
Node next;
Node(String val, Node p, Node n) {
value = val;
prev = p;
next = n;
}
Node(String val) {
value = val;
prev = null;
next = null;
}
}
Node first;
Node last;
public doubleLinkedList() {
first = null;
last = null;
}
public boolean isEmpty() {
if (first == null)
return true;
else
return false;
}
/**The size method returns the length of the linked list
* #return the number of element in the linked list
*/
public int size() {
int count = 0;
Node traverse = first;
while (traverse != null) {
count++;
traverse = traverse.next;
}
return count;
}
public void add(String element) {
if (isEmpty()) {
first = new Node(element);
last = first;
} else {
Node p = first;
Node elementTobeAdded;
while (((p.value).compareTo(element)) > 0 && p.next != null) {
p = p.next;
}
if (p.next != null) {
elementTobeAdded = new Node(element, p, p.next);
p.next.prev = elementTobeAdded;
p = elementTobeAdded.prev;
} else {
elementTobeAdded = new Node(element, p, null);
p.next = elementTobeAdded;
elementTobeAdded.next = null;
last = elementTobeAdded;
}
}
}
public void printForward() {
Node printNode = first;
while (printNode != null) {
System.out.print(printNode.value + ", ");
printNode = printNode.next;
}
}
}
public class test {
public static void main(String[] args) {
doubleLinkedList car = new doubleLinkedList();
car.add("Jeep");
car.add("benz");
car.add("Honda");
car.add("Lexus");
car.add("BMW");
car.printForward();
}
}
My add method is trying to add nodes to a list in alphabetical order. My printForward method prints out each element in the list.
In my main method, it prints out "Jeep, benz, Honda, BMW,", which is not in alphabetical order.
Change the not empty case for your add method from this
Node p = first;
Node elementTobeAdded;
while(((p.value).compareTo(element)) > 0 && p.next != null)
{
p = p.next;
}
if(p.next != null)
{
elementTobeAdded = new Node(element,p,p.next);
p.next.prev = elementTobeAdded;
p = elementTobeAdded.prev;
}
else
{
elementTobeAdded = new Node(element, p, null);
p.next = elementTobeAdded;
elementTobeAdded.next = null;
last = elementTobeAdded;
}
to this:
Node p = first;
while (p.value.compareTo(element) < 0 && p.next != null) {
p = p.next;
}
if (p.value.compareTo(element) > 0) {
Node toAdd = new Node(element, p.prev, p);
p.prev = toAdd;
if (toAdd.prev != null) {
toAdd.prev.next = toAdd;
}else {
first = toAdd;
}
}else {
Node toAdd = new Node(element, p, p.next);
p.next = toAdd;
if (toAdd.next != null) {
toAdd.next.prev = toAdd;
}else {
last = toAdd;
}
}
There were many errors here. The biggest one was that you never checked for the case where the new element should be inserted at the beginning of the list. A new element was always inserted after the first element even if it should have come first.
Note that "benz" comes at the end because the String.compareTo method treats capitals as coming before lower case letters.
It is not an a linked list... You wrote some sort of Queue (with optional possibility to make it Dequeue).
About your question - you have an error in your 'add' method - at least you don't check if it is necessary to move head forward. It is possible that you have another bugs, but it is too hard to read such styled sources (please fix your question formatting)...
I'm stuck on this problem:
You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1’s digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.
EXAMPLE
Input: (3 -> 1 -> 5), (5 -> 9 -> 2)
Output: 8 -> 0 -> 8
The problem is that my result is 8 8 while the result should be 8 0 8.
I printed out the sum and it is 8 10 8 so it should work.
Any ideas?
Here is my code:
public Node addNumbers(Node number1, Node number2) {
if(number1 == null && number2 == null)
return null;
Node sumOf = null;
int sum = 0;
int carry = 0;
while(number1 != null && number2 != null) {
sum = number1.data + number2.data + carry;
System.out.println(sum);
// update carry for next operation
if(sum > 9)
carry = 1;
else
carry = 0;
if(sum > 9) {
if(sumOf == null) {
sumOf = new Node(sum % 10);
} else {
sumOf.next = new Node(sum % 10);
}
} else {
if(sumOf == null) {
sumOf = new Node(sum);
} else {
sumOf.next = new Node(sum);
}
}
number1 = number1.next;
number2 = number2.next;
}
return sumOf;
}
public void toString(Node node) {
System.out.println();
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
}
public static void main(String[] args) {
AddTwoNumbers add = new AddTwoNumbers();
number1 = new Node(3);
number1.next = new Node(1);
number1.next.next = new Node(5);
number2 = new Node(5);
number2.next = new Node(9);
number2.next.next = new Node(2);
System.out.println("numbers: ");
add.toString(number1);
add.toString(number2);
System.out.println();
System.out.println("after adding: ");
add.toString(add.addNumbers(number1, number2));
}
}
You only ever set sumOf (if it is null) and sumOf.next (if sumOf is not null). Your resulting list therefore never has more than two elements. You need to track the current tail of your list and append there, instead of always appending to sumOf.
Additionally, you need to handle the cases where one input number has more digits than the other, and where you have non-zero carry after exhausting all the input digits. You do not presently handle either.
Here is the solution, do note that i carry forward when the sum of two integers is greater than 9 else i 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]
**#In Python:-**
class Node():
def __init__(self,value):
self.value=value
self.nextnode=None
class LinkedList():
def __init__(self):
self.head=None
def add_element(self,value):
node=Node(value)
if self.head is None:
self.head =node
return
crnt_node=self.head
while crnt_node.nextnode is not None:
crnt_node=crnt_node.nextnode
crnt_node.nextnode=node
def reverse_llist(self):
crnt_node=self.head
if crnt_node == None:
print('Empty Linkned List')
return
old_node = None
while crnt_node:
temp_node = crnt_node.nextnode
crnt_node.nextnode = old_node
old_node = crnt_node
crnt_node = temp_node
self.head = old_node
def converted_llist(self):
crnt_node=self.head
carry_value=0
while True:
#print(crnt_node.value)
if (crnt_node.value+1)%10==0:
carry_value=1
crnt_node.value=0
print(crnt_node.value,end='->')
else:
print(crnt_node.value+carry_value,end='->')
if crnt_node.nextnode is None:
break
crnt_node=crnt_node.nextnode
print('None')
def print_llist(self):
crnt_node=self.head
while True:
print(crnt_node.value,end='->')
if crnt_node.nextnode is None:
break
crnt_node=crnt_node.nextnode
print('None')
list_convert=LinkedList()
list_convert.add_element(1)
list_convert.print_llist()
list_convert.add_element(9)
list_convert.print_llist()
list_convert.add_element(9)
list_convert.print_llist()
list_convert.add_element(9)
list_convert.print_llist()
list_convert.reverse_llist()
list_convert.print_llist()
list_convert.converted_llist()
I need help making this toString method pass the tests at the bottom. I am currently getting the error (expected:<0:20, 1:[1]0> but was <0:20, 1:[2]0>). addFirst is working 100%, but I'm not sure what is wrong here.
public class LList
{
public Node head;
private int i;
private int size;
public void addFirst(int value)
{
Node n = new Node();
n.value = value;
n.next = head;
head = n;
}
public void removeFirst()
{
if (head != null)
{
// commone case: there is at least one node
head = head.next;
}
else
{
// no nodes
throw new Banana();
}
}
public int size()
{
Node current = head;
int count = 0;
while(current != null)
{
count++; // keep count of nodes
current = current.next; // move to next node
}
return count;
}
public int get(int index)
{
int count = 0;
Node current = head;
if (index < 0 || index >= size())
{
throw new Banana();
}
while(count != index)
{
count++;
current = current.next;
}
return current.value;
}
public String toString()
{
String s = "";
Node current = head;
//current = head;
if (size() == 0)
{
return s;
}
else
{
s = s + "" + i + ":" + current.value;
for (int i = 1; i < size(); i++)
{
s = s + ", " + i + ":" + current.value;
}
return s;
}
}
public class Node
{
public int value;
public Node next;
}
#Test
public void testToString()
{
LList a = new LList();
assertEquals("", a.toString());
a.addFirst(10);
assertEquals("0:10", a.toString());
a.addFirst(20);
assertEquals("0:20, 1:10", a.toString());
a.addFirst(30);
assertEquals("0:30, 1:20, 2:10", a.toString());
}
You should iterate (walk over) all Nodes.
Use while loop for that, e.g.:
public String toString() {
String s = "";
Node current = head;
// current = head;
if (size() != 0) {
int i = 0;
s = s + "" + i + ":" + current.value;
while(current.next != null) {
i++;
current = current.next;
s = s + ", " + i + ":" + current.value;
}
}
return s;
}
Hey I can't seem to get my code to work, there is something wrong with the constructor and I just can't figure out what it is.
I had it working for the constructor and tried it for some of the methods but even then it still gave me NullPointerException
import java.util.NoSuchElementException;
public class LinkedString
{
//Required Nodes/counters to track positions in LinkedList
private Node start;
private Node end;
private int counter;
private int i = 0;
//Inner class Node provides the node object required to create links
private class Node
{
public char data;
public Node next;
}
//This constructor allows the user to input a array of characters
//and have them created into a LinkedString object
public LinkedString(char[] value)
{
start.data = value[0];
counter = 0;
for(int i = 0 ; i < value.length ; i++)
{
if ( start == null)
{
start.data = value[i];
start.next = end;
counter++;
}
else
{
Node newNode = new Node();
newNode.data = value[i];
end.next = newNode;
newNode.next = null;
end = newNode;
counter++;
}
}
}
//This constructor allows the user to input a String
//getting each character and creating it into a LinkedString object
public LinkedString(String value)
{
counter=0;
for(int i = 0; i < value.length(); i++)
{
if(start == null)
{
start.data = value.charAt(i);
start.next = end;
counter++;
}
else
{
Node newNode = new Node();
newNode.data=value.charAt(i);
end.next = newNode;
newNode.next = null;
end = newNode;
}
}
}
//This accessor returns a value at the specified index
//The 1st character has an index of 0 and will throw
//a no such element exception if there is no char # given index
public char charAt(int index)
{
Node current = start;
boolean found = false;
char temp = 0;
int i = 0;
while (current.next != null && i <= index)
{
current = current.next;
if(i == index)
{
found = true;
//Return done, and Data is wrong Edit.
}
i++;
temp = current.data;
}
if(found == false) {
throw new NoSuchElementException();
}
return temp;
}
//concat connects two linkedString objects together and updates the
//counter for how many chars are in the combined list
public LinkedString concat(LinkedString value)
{
end.next = value.start;
end = value.end;
counter = counter + value.length();
return value;
}
//isEmpty checks to see if the list has a initial value
//if it doesnt its empty and returns true
public boolean isEmpty()
{
if(start == null)
{
return true;
}
else
{
return false;
}
}
//length() returns the counter variable which counts the number of
// characters in the linked string
public int length()
{
return counter;
}
//substring returns a copy of the linked string from a specified point
//to another, if the user attempts to copy a value from a not existing
//index point it throws NoSuchElementException
public Node substring(int startIndex, int endIndex)
{
Node current = start;
Node sIndex;
Node eIndex;
Node copy = null;
int i = 0;
while(current.next != null && i <= startIndex)
{
current = current.next;
if(i == startIndex)
{
sIndex = current;
sIndex.next = copy;
while(current.next != null && i <= endIndex)
{
current = current.next;
copy.next = current;
copy = current;
if(i == endIndex)
{
eIndex = current;
eIndex.next = null;
copy.next = eIndex;
}
i++;
}
if(i < endIndex)
throw new NoSuchElementException();
}
i++;
}
return copy;
}
}
public class LinkedStringMain {
public static void main(String[] args) {
LinkedString linked = new LinkedString("stack");
System.out.println(" " + linked.charAt(0));
System.out.println(" " + linked.isEmpty());
}
}
The error is that start is not being initialized in your either of your constructors after you check if it is null. To fix this, initialize start using start = new Node();. The changes are implemented below:
//This constructor allows the user to input a array of characters
//and have them created into a LinkedString object
public LinkedString(char[] value)
{
start.data = value[0];
counter = 0;
for(int i = 0 ; i < value.length ; i++)
{
if ( start == null)
{
start = new Node(); //initialize start
start.data = value[i];
start.next = end;
counter++;
}
else
{
Node newNode = new Node();
newNode.data = value[i];
end.next = newNode;
newNode.next = null;
end = newNode;
counter++;
}
}
}
//This constructor allows the user to input a String
//getting each character and creating it into a LinkedString object
public LinkedString(String value)
{
counter=0;
for(int i = 0; i < value.length(); i++)
{
if(start == null)
{
start = new Node(); //initialize start
start.data = value.charAt(i);
start.next = end;
counter++;
}
else
{
Node newNode = new Node();
newNode.data=value.charAt(i);
end.next = newNode;
newNode.next = null;
end = newNode;
}
}
}
I have this school assignment that I'm a little confused about.
Here's what it's saying:
"Write a program that uses the technique of 'chaining' for hashing.
The program will read in the length of an array which will contain the reference to each
linked list that will be generated. Furthermore, all values that are to be stored, is read.
The program shall have a separate function for hashing where the index exists. When the program have generated the linked lists, the theoretical 'load factor' is to be calculated and printed out. The whole array should be easily printed out."
The thing that I'm confused about, is the part about the program will read in the length of an array which will contain the reference to each linked list that will be generated. Is it possible to generate multiple linked lists? In that case, how do you do that?
This is the classes I'm told to use:
public class EnkelLenke {
private Node head = null;
private int numOfElements = 0;
public int getNum()
{
return numOfElements;
}
public Node getHead()
{
return head;
}
public void insertInFront(double value)
{
head = new Node (value, head);
++numOfElements;
}
public void insertInBack(double value)
{
if (head != null)
{
Node this = head;
while (this.next != null)
this = this.next;
this.next = new Node(value, null);
}
else
head = new Node(value, null);
++numOfElements;
}
public Node remove(Node n)
{
Node last = null;
Node this = head;
while (this != null && this != n)
{
last = this;
this = this.next;
}
if (this != null)
{
if (last != null)
last.next = this.next;
else
head = this.next;
this.next = null;
--numOfElements;
return this;
}
else
return null;
}
public Node findNr(int nr)
{
Node this = head;
if (nr < numOfElements)
{
for (int i = 0; i < nr; i++)
this = this.next;
return this;
}
else
return null;
}
public void deleteAll()
{
head = null;
numOfElements = 0;
}
public String printAllElements() {
String streng = new String();
Node this = head;
int i = 1;
while(this != null)
{
streng = streng + this.element + " ";
this = this.findNext();
i++;
if(i > 5)
{
i = 1;
streng = streng + "\n";
}
}
return streng;
}
public double getValueWithGivenNode (Node n)
{
Node this = head;
while (this != null && this != n)
{
this = this.next;
}
if (this == n)
return this.element;
else
return (Double) null;
}
}
public class Node {
double element;
Node next;
public Node(double e, Node n)
{
element = e;
next = n;
}
public double findElement()
{
return element;
}
public Node findNext()
{
return next;
}
}
Your data structure will look something like this (where "LL" is a linked list):
i | a[i]
-------------------------------
0 | LL[obj1 -> obj5 -> obj3]
1 | LL[obj2]
2 | LL[]
... | ...
N-1 | LL[obj4 -> obj6]
At each array index, you have a linked list of objects which hash to that index.
Is it possible to generate multiple linked lists? In that case, how do you do that?
Yes. Create your array, and initialize each element to a new linked list.
EnkelLenke[] a = new EnkelLenke[N];
for ( int i = 0; i < N; i++ ) {
a[i] = new EnkelLenke();
}