I have this school activity where we are asked to create our own class that implements a LinkedList. I have this problem regarding deleting nodes at a specific position. Can someone help me with this one? Please see attached screenshot:
I'll appreciate also if maybe you can help me with this additional functions:
This is what I came up so far:
public void deleteAtPosition(int position){
if(isEmpty()){
error_message("The list is empty. Try to add a value.");
}
else if(position == 0){
deleteAtFirst();
}
else if (position < 0 || position >= currentSize()){
error_message("Position is NOT valid.");
}
else{
LNode visit, link, pointer;
visit=link=pointer=head;
int ctr = 0;
while(ctr != position){
visit = visit.next;
ctr++;
}
while(link.next != visit){
link = link.next;
}
ctr = 1;
while(ctr != position){
pointer = pointer.next;
ctr--;
}
link.next = pointer;
}
}
Related
Could anyone explain why the following delete method does not work? It appears to create an infinite loop at the value I am trying to remove. It should loop through a linked list, delete all instances of the value passed to the method, and return the total number of nodes deleted (return num;).
public int delete(T value)
{
int num = 0;
ListNode<T> trav = head;
ListNode<T> next = head.getNext();
while(trav != null) {
if(trav.getValue().compareTo(value) == 0) {
trav = next;
num++;
}
if(next.getValue().compareTo(value) == 0) {
trav = next.getNext();
num++;
}
trav = trav.getNext();
}
return num;
}
You never change the value of next.
if(trav.getValue().compareTo(value) == 0) {
trav = next;
num++;
}
if(next.getValue().compareTo(value) == 0) {
trav = next.getNext();
num++;
}
Since next never changes, you're comparing the same value in the second if every time.
I have looked at a lot of other answers on stackoverflow and can't find anything that works, I either get the root, or node1 itself returned, I'm not sure how to do this recursively and have tried it many times all ending the same way. Any help would be greatly appreciated!
Here's my code:
private static Node findLCA(Node node1, Node node2) {
Node temp1 = node1, temp2 = node2, currentLargest = null;
int largestDepth = 0;
boolean found = false;
if(node1 == null || node2 == null){
return null;
} else{
while(found == false){
if(temp1.getParent() != null && temp2.getParent() != null && temp1.getParent() == temp2.getParent() && nodeDepth(temp1.getParent()) > largestDepth){
largestDepth = nodeDepth(temp1.getParent());
currentLargest = temp1;
temp1 = temp1.getParent();
temp2 = temp2.getParent();
} else if(temp1.getParent() != null){
temp1 = temp1.getParent();
} else if(temp2.getParent() != null){
temp2 = temp2.getParent();
}
if(temp1.getParent() == null && temp2.getParent() == null){
found = true;
}
}
if(nodeDepth(temp1) >= largestDepth){
return temp1;
} else{
return currentLargest;
}
}
}
I edited it to make a list of ancestors of each node, but I'm not sure how to go around checking each one to see if the elements in the list's match up since they are usually different sizes.
Heres the new code:
ArrayList<PhyloTreeNode> list1 = new ArrayList<PhyloTreeNode>();
ArrayList<PhyloTreeNode> list2 = new ArrayList<PhyloTreeNode>();
if(node1 == null || node2 == null){
return null;
} else{
if(node1.getParent() != null){
list1.add(node1.getParent());
findLeastCommonAncestor(node1.getParent(), node2);
}
if(node2.getParent() != null){
list2.add(node2.getParent());
findLeastCommonAncestor(node1, node2.getParent());
}
}
We can use recursive post order traversal for computing lowest common ancestor,
Here is my Java implementation
Here a & b are given input data for which i have to find lowest common ancestors.
public static int lowestcommanancestors(Node root,int a,int b){
if(root==null)
return 0;
int x=lowestcommanancestors(root.left,a,b);
int y=lowestcommanancestors(root.right,a,b);
if(x+y==2){
System.out.println(root.getData());
return 0;
}
if(root.getData()==a || root.getData()==b){
return x+y+1;
}
else{
return x+y;
}
}
First i am checking whether given input node presenting in left subtree or not,if yes just return 1 else 0,Similarly for right sub tree.When sum becomes 2 first time that node will be lowest common ancestors.
Tell me if i am wrong or you are getting difficulties to understanding the code
For our homework, I have to take in Chair objects and add them to the DoublyLinkedList that we made; it has to be sorted by alphabetical order, if style is the same alphabetically, we sort by color
When I try to go through the loop, I keep getting a NullPointerException.
public void add(Chair element){
if(isEmpty() || first.object.style.compareTo(element.style) > 0 || (first.object.style.compareTo(element.style) == 0 && first.object.color.compareTo(element.color) >= 0){
addFirst(element);
}else if(first.object.style.compareTo(element.style) <= 0){
Node temp = first;
Node insert = new Node(); insert.object = element;
while(temp.object.style.compareTo(element.style) <= 0) //This is where the nullPointerException occurs
if(temp.hasNext())
temp = temp.next;
while(temp.object.style.compareTo(element.style) == 0 && temp.object.color.compareTo(element.color) <= 0)
if(temp.hasNext())
temp = temp.next;
insert.prev = temp.prev;
insert.next = temp;
temp.prev.next = insert;
temp.prev = insert;
}
}
This is the code where I put the information into the DoublyLinkedList
try{
FileReader fr = new FileReader(filename);
Scanner sc = new Scanner(fr);
String[] temp;
while(sc.hasNext()){
temp = sc.nextLine().split(" ");
if(temp[0].equals("Bed")){}
else if(temp[0].equals("Table")){
// tables.add(new Table(Integer.parseInt(temp[1]), Integer.parseInt(temp[2]), Integer.parseInt(temp[3]), temp[4]));
}else if(temp[0].equals("Desk")){}
else if(temp[0].equals("Chair")){
chairs.add(new Chair(temp[1], temp[2]));
}else if(temp[0].equals("Bookshelves")){}
else{
color = temp[0];
}
}
while(!chairs.isEmpty())
System.out.println(chairs.removeFirst().info());
System.out.println();
//while(!tables.isEmpty())
// System.out.println(tables.removeFirst().info());
}catch(Exception e){e.printStackTrace();}
This is the DoublyLinkedList class that I've made:
class CDoublyLinkedList{
Node first, last;
public CDoublyLinkedList(){
first = new Node(); last = new Node();
first.prev = last.next = null;
first.object = last.object = null;
first.next = last;
last.prev = first;
}
public boolean isEmpty(){
return first.object == null;
}
public void addFirst(Chair element){
Node insert = new Node();
insert.object = element;
insert.prev = null;
insert.next = first;
first.prev = insert;
first = insert;
}
public void add(Chair element){
if(isEmpty() || first.object.style.compareTo(element.style) > 0 || (first.object.style.compareTo(element.style) == 0 && first.object.color.compareTo(element.color) >= 0){
addFirst(element);
}else if(first.object.style.compareTo(element.style) <= 0){
Node temp = first;
Node insert = new Node(); insert.object = element;
while(first.object.style.compareTo(element.style) <= 0)
if(temp.hasNext())
temp = temp.next;
while(first.object.style.compareTo(element.style) == 0 && first.object.color.compareTo(element.color) <= 0)
if(temp.hasNext())
temp = temp.next;
insert.prev = temp.prev;
insert.next = temp;
temp.prev.next = insert;
temp.prev = insert;
}
}
public Chair removeFirst(){
Chair tobedeleted = first.object;
Node temp = first.next;
first = temp;
first.prev = null;
return tobedeleted;
}
private class Node{
Node next, prev;
Chair object;
public boolean hasNext(){
return next != null;
}
}
}
The Chair class:
class Chair extends Furniture{
public String style, color;
public Chair(String s, String c){
style = s; color = c;
}
public String toString(){
return color;
}
public String getType(){
return "Chair";
}
public String info(){
return (color+", "+style);
}
}
Can someone please explain to me why I keep getting this error? Thank you!
EDIT:
while(temp.object.style.compareTo(element.style) <= 0) //This is where the nullPointerException occurs
chairs.add(new Chair(temp[1], temp[2]));
java.lang.NullPointerException
at CDoublyLinkedList.add(Furnish2SS.java:119)
at Furnish2SS.main(Furnish2SS.java:23)
java.lang.NullPointerException
at CDoublyLinkedList.add(Furnish2SS.java:119)
at Furnish2SS.main(Furnish2SS.java:23)
EDIT2: SOLVED!
I changed my while loop to:
while(temp.object != null && element != null && (temp.object.compareTo(element) == 0 || temp.object.compareTo(element) == -1))
The reason I got the error was because I wasn't checking for null every iteration.
You say this is the line of code causing the exception:
while(temp.object.style.compareTo(element.style) <= 0)
You probably should set a debugger breakpoint on that line and use a debugger to determine which of the values is null. But it's hard for me to explain here full instructions on how to setup and use a debugger (that doesn't mean you shouldn't learn! You should. There are lots of tutorials. Google it.) So instead of writing a tutorial on debuggers, I'll just post code that will tell you which variable is null:
if (temp == null) {
System.out.println("temp is null");
} else if (temp.object == null) {
System.out.println("temp.object is null");
} else if (temp.object.style == null) {
System.out.println("temp.object.style is null");
}
if (element == null) {
System.out.println("element is null");
} else if (element.style == null) {
System.out.println("element.style is null");
}
while(temp.object.style.compareTo(element.style) <= 0) //This is where the nullPointerException occurs
{
if(temp.hasNext())
temp = temp.next;
if (temp == null) {
System.out.println("loop: temp is null");
} else if (temp.object == null) {
System.out.println("loop: temp.object is null");
} else if (temp.object.style == null) {
System.out.println("loop: temp.object.style is null");
}
if (element == null) {
System.out.println("loop: element is null");
} else if (element.style == null) {
System.out.println("loop: element.style is null");
}
}
If you use the above code statements to replace these three lines of your code:
while(temp.object.style.compareTo(element.style) <= 0) //This is where the nullPointerException occurs
if(temp.hasNext())
temp = temp.next;
you will know which variable is null based on which statement is printed. Hopefully you can take it from there. (The usual way to fix a NullPointerException is to take the steps necessary to ensure the offending null variable actually has a valid, non-null value by the time the program reaches the line of the NullPointerException).
Take a look at addFirst(Chair element). That method is really screwed up. It creates a new Node which contains the correct Chair. It then sets its prev to null. Then it sets next to first. And this is what's causing all of your troubles. Because first points to an empty Node. You end up with this:
first points to your new Node. That one points to a Node which holds no Chair. That one again points to last.
e:
Your whole code looks like you had at least two different approaches on implementing your list and threw them toghether. There are some more errors but since this is homework I guess it's not that bad if you try fixing it first.
If you can't figure out how to correct that, ask here.
PS: Sorry for all of the editing and (un)deleting my answeres (if you noticed). I'm a bit tired and kept causing new errors by fixing old ones until I finally figured out what was the true cause of all this.
I am running BlueJ as my IDE. For some odd reason I get an error in this line of code:
import javax.swing.*;
public class RotateArrayCircularLL
{
private Node head=null;
// ==================================================================================
public void init()
{
int choice = 0;
while (choice != -1){
choice = Integer.parseInt(JOptionPane.showInputDialog("Enter -1 to stop loop, 1 to continue"));
if(choice == -1)
break;
inputNum();
}
printList();
}
public void inputNum()
{
Node n;
Node temp;
int k;
k = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter a number:"));
n = new Node(k);
if (head == null) {
head = n;
} else {
temp = head;
while (temp.getNext() != null)
temp = temp.getNext();
temp.setNext(n);
}
}
public void printList()
{
Node temp = head;
Node d, e;
int count = Integer.parseInt(JOptionPane.showInputDialog("Enter the value to shift to the right"));
for (int i = 1; i <= count; i++) // Rotates the head
temp = temp.getNext();
for (e = head; e != null; e = e.getNext()){
if (e.getNext() != null)
System.out.print(e.getInfo() + "-");
if (e.getNext() == null)
System.out.print(e.getInfo());
}
for (Node c = temp; c != null && c.getNext() != head; c= c.getNext()){
System.out.print(c.getInfo() + "-");
}
for (d = head; d != null && d.getNext() != temp; d = d.getNext())
{
System.out.print(d.getInfo()+ "-");
}
System.out.println(d.getInfo());
}
}
The error is: Cannot find symbol- method getNext().
The code was working perfectly before but recently my compiler froze and was not responding so I ended the process via Task Manager. Since then it started to act up.
Can anyone explain why it is not working? I don't think that it is my issue, but rather the compilers.
The likely cases are either:
The method getNext() does not exist within the Node class, or
the calling signature of getNext() doesn't match with how it's defined (despite it being an accessor).
I can't say for certain which line of code is causing it, as you haven't provided code for the Node class. However, comb through the Node class and make certain that both getNext() exists, and you're calling it the way you're supposed to (passing valid arguments, and so forth).
Check the xml files. I had the same problem. I was calling a TextView that I previously rename and forgot to change the name.
import javax.swing.JOptionPane;
public class RotateArrayCircularLL
{
private Node head=null;
public void init()
{
int choice = 0;
while (choice != -1){
choice = Integer.parseInt(JOptionPane.showInputDialog("Enter -1 to stop loop, 1 to continue"));
if(choice == -1)
break;
inputNum();
}
printList();
}
public void inputNum()
{
Node n;
Node temp;
int k;
k = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter a number:"));
n = new Node(k);
if (head == null) {
head = n;
} else {
temp = head;
while (temp.getNext() != null)
temp = temp.getNext();
temp.setNext(n);
}
}
public void printList()
{
Node temp = head;
int count = Integer.parseInt(JOptionPane.showInputDialog("Enter the value to shift to the right"));
for (int i = 1; i <= count; i++) // Rotates the head
temp = temp.getNext();
for (Node c = temp; c != null && c.getNext() != head; c= c.getNext()){ // Prints the new LL
System.out.print(c.getInfo());
}
}
}
I get an NPE during the second for loop. I understand that it is giving me a NPE because I reach the end of the list, but how can I stop it from doing this?
It appears from the behavior you are seeing that one of the nodes in your linked list is returning null instead of the next element of the list. At a guess, I'd suggest that the last node of your list is probably not pointing to the first node of your list. Hence as Hovercraft Full Of Eels suggests, you don't really have a properly circular linked list. If you can post the code showing how temp is populated, it may be possible to give a more concrete solution to your issue. Otherwise, you need to treat the case where getNext() returns null as a special case and ensure that you instead get the first element from the initial list.