Splitting a Linked List at a Given Node, into Two Sublists??
My code just will not work!! Any help would be appreciated! My problem is in the last method SplitAt. These are the conditions set and my code:
Splitting a Linked List at a Given Node, into Two Sublists
a. Add the following as an abstract method to the class
LinkedListClass:
public void splitAt (LinkedListClass<T> secondList, T item);
//This method splits the list at the node with the info item into two sublists.
//Precondition: The list must exist.
//Postcondition: first and last point to the first and last nodes of the first sublist,
// respectively. secondList.first and secondList.last point to the first
// and last nodes of the second sublist.
Consider the following statements:
UnorderedLinkedList<Integer> myList;
UnorderedLinkedList<Integer> otherList;
Suppose myList points to the list with the elements 34, 65, 18, 39, 27, 89, and 12 (in this order). The statement
myList.splitAt(otherList, 18);
splits myList into two sublists: myList points to the list with elements 34 and 65, and otherList points to the sublist with elements 18, 39, 27, 89, and 12.
b. Provide the definition of the method splitAt in the class UnorderedLinkedList. Also write a program to test your method.
public class UnorderedLinkedList<T> extends LinkedListClass<T>
//Default constructor
public UnorderedLinkedList()
super();
//Method to determine whether searchItem is in
//the list.
//Postcondition: Returns true if searchItem is found
// in the list; false otherwise.
public boolean search(T searchItem)
LinkedListNode<T> current; //variable to traverse
//the list
boolean found;
current = first; //set current to point to the first
//node in the list
found = false; //set found to false
while (current != null && !found) //search the list
if (current.info.equals(searchItem)) //item is found
found = true;
else
current = current.link; //make current point to
//the next node
return found;
//Method to insert newItem in the list.
//Postcondition: first points to the new list
// and newItem is inserted at the
// beginning of the list. Also,
// last points to the last node and
// count is incremented by 1.
public void insertFirst(T newItem)
LinkedListNode<T> newNode; //variable to create the
//new node
newNode =
new LinkedListNode<T>(newItem, first); //create and
//insert newNode before
//first
first = newNode; //make first point to the
//actual first node
if (last == null) //if the list was empty, newNode is
//also the last node in the list
last = newNode;
count++; //increment count
//Method to insert newItem at the end of the list.
//Postcondition: first points to the new list and
// newItem is inserted at the end
// of the list. Also, last points to
// the last node and
// count is incremented by 1.
public void insertLast(T newItem)
LinkedListNode newNode; //variable to create the
//new node
newNode =
new LinkedListNode(newItem, null); //create newNode
if (first == null) //if the list is empty, newNode is
//both the first and last node
first = newNode;
last = newNode;
else //if the list is not empty, insert
//newNode after last
last.link = newNode; //insert newNode after last
last = newNode; //set last to point to the
//actual last node
count++;
}//end insertLast
//Method to delete deleteItem from the list.
//Postcondition: If found, the node containing
// deleteItem is deleted from the
// list. Also, first points to the first
// node, last points to the last
// node of the updated list, and count
// is decremented by 1.
public void deleteNode(T deleteItem)
LinkedListNode<T> current; //variable to traverse
//the list
LinkedListNode<T> trailCurrent; //variable just
//before current
boolean found;
if ( first == null) //Case 1; the list is empty
System.err.println("Cannot delete from an empty "
+ "list.");
else
if (first.info.equals(deleteItem)) //Case 2
first = first.link;
if (first == null) //the list had only one node
last = null;
count--;
else //search the list for the given info
found = false;
trailCurrent = first; //set trailCurrent to
//point to the first node
current = first.link; //set current to point to
//the second node
while (current != null && !found)
if (current.info.equals(deleteItem))
found = true;
else
trailCurrent = current;
current = current.link;
}//end while
if (found) //Case 3; if found, delete the node
count--;
trailCurrent.link = current.link;
if (last == current) //node to be deleted
//was the last node
last = trailCurrent; //update the value
//of last
else
System.out.println("Item to be deleted is "
+ "not in the list.");
}//end else
}//end else
}//end deleteNode
public void splitAt(LinkedListClass<T> secondList, T item)
LinkedListNode<T> current;
LinkedListNode<T> trailCurrent;
int i;
boolean found;
if (first==null)
System.out.println("Empty.");
first=null;
last=null;
count--;
else
current=first;
found=false;
i=1;
while(current !=null &&!found)
if(current.info.equals(secondList))
found= true;
else
trailCurrent=current;
i++;
if(found)
if(first==current)
first=first;
last=last;
count=count;
count=0;
else
first=current;
last=last;
last=null;
count = count- i+1;
count = i-1;
else
System.out.println("Item to be split at is "
+ "not in the list.");
first=null;
last=null;
count=0;
}
I dont have a test program at all. The program is supposed to prompt for user input of numbers. (it does) Take the input and end at input of -999 (it does). Then it asks user where it wants to split list (it does). When I enter a number it does nothing after that. I am going to post updated code and see if that helps along with all the classes. Thanks!
This is the class to prompt:
import java.util.*;
public class Ch16_ProgEx6
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
UnorderedLinkedList<Integer> list
= new UnorderedLinkedList<Integer>();
UnorderedLinkedList<Integer> subList =
new UnorderedLinkedList<Integer>();
Integer num;
System.out.println("Enter integers ending with -999.");
num = console.nextInt();
while (num != -999)
list.insertLast(num);
num = console.nextInt();
System.out.println();
System.out.println("list: ");
list.print();
System.out.println();
System.out.println("Length of list: " + list.length());
System.out.print("Enter the number at which to split list: ");
num = console.nextInt();
list.splitAt(subList, num);
System.out.println("Lists after splitting list");
System.out.print("list: ");
list.print();
System.out.println();
System.out.println("Length of list: " + list.length());
System.out.print("sublist: ");
subList.print();
System.out.println();
System.out.println("Length of sublist: " + subList.length());
}This is the ADT:
public interface LinkedListADT<T> extends Cloneable
public Object clone();
//Returns a copy of objects data in store.
//This method clones only the references stored in
//each node of the list. The objects that the
//list nodes point to are not cloned.
public boolean isEmptyList();
//Method to determine whether the list is empty.
//Postcondition: Returns true if the list is empty;
// false otherwise.
public void initializeList();
//Method to initialize the list to an empty state.
//Postcondition: The list is initialized to an empty
// state.
public void print();
//Method to output the data contained in each node.
public int length();
//Method to return the number of nodes in the list.
//Postcondition: The number of nodes in the list is
// returned.
public T front();
//Method to return a reference of the object containing
//the data of the first node of the list.
//Precondition: The list must exist and must not be empty.
//Postcondition: The reference of the object that
// contains the info of the first node
// is returned.
public T back();
//Method to return a reference of object containing
//the data of the last node of the list.
//Precondition: The list must exist and must not be empty.
//Postcondition: The reference of the object that
// contains the info of the last node
// is returned.
public boolean search(T searchItem);
//Method to determine whether searchItem is in the list.
//Postcondition: Returns true if searchItem is found
// in the list; false otherwise.
public void insertFirst(T newItem);
//Method to insert newItem in the list.
//Postcondition: newItem is inserted at the
// beginning of the list.
public void insertLast(T newItem);
//Method to insert newItem at the end of the list.
//Postcondition: newItem is inserted at the end
// of the list.
public void deleteNode(T deleteItem);
//Method to delete deleteItem from the list.
//Postcondition: If found, the node containing
// deleteItem is deleted from the
// list.
public void splitAt(LinkedListClass<T> secondList, T item);
}This is the linked list class:
import java.util.NoSuchElementException;
public abstract class LinkedListClass<T> implements LinkedListADT<T>
protected class LinkedListNode<T> implements Cloneable
public T info;
public LinkedListNode<T> link;
//Default constructor
//Postcondition: info = null; link = null;
public LinkedListNode()
info = null;
link = null;
//Constructor with parameters
//This method sets info pointing to the object to
//which elem points to and link is set to point to
//the object to which ptr points to.
//Postcondition: info = elem; link = ptr;
public LinkedListNode(T elem, LinkedListNode<T> ptr)
info = elem;
link = ptr;
//Returns a copy of objects data in store.
//This method clones only the references stored in
//the node. The objects that the nodes point to
//are not cloned.
public Object clone()
LinkedListNode<T> copy = null;
try
copy = (LinkedListNode<T>) super.clone();
catch (CloneNotSupportedException e)
return null;
return copy;
//Method to return the info as a string.
//Postcondition: info as a String object is
// returned.
public String toString()
return info.toString();
} //end class LinkedListNode
public class LinkedListIterator<T>
protected LinkedListNode<T> current; //variable to
//point to the
//current node in
//list
protected LinkedListNode<T> previous; //variable to
//point to the
//node before the
//current node
//Default constructor
//Sets current to point to the first node in the
//list and sets previous to null.
//Postcondition: current = first; previous = null;
public LinkedListIterator()
current = (LinkedListNode<T>) first;
previous = null;
//Method to reset the iterator to the first node
//in the list.
//Postcondition: current = first; previous = null;
public void reset()
current = (LinkedListNode<T>) first;
previous = null;
//Method to return a reference of the info of the
//current node in the list and to advance iterator
//to the next node.
//Postcondition: previous = current;
// current = current.link;
// A refrence of the current node
// is returned.
public T next()
if (!hasNext())
throw new NoSuchElementException();
LinkedListNode<T> temp = current;
previous = current;
current = current.link;
return temp.info;
//Method to determine whether there is a next
//element in the list.
//Postcondition: Returns true if there is a next
// node in the list; otherwise
// returns false.
public boolean hasNext()
return (current != null);
//Method to remove the node currently pointed to
//by the iterator.
//Postcondition: If iterator is not null, then the
// node that the iterator points to
// is removed. Otherwise the method
// throws NoSuchElementException.
public void remove()
if (current == null)
throw new NoSuchElementException();
if (current == first)
first = first.link;
current = (LinkedListNode<T>) first;
previous = null;
if (first == null)
last = null;
else
previous.link = current.link;
if (current == last)
last = first;
while (last.link != null)
last = last.link;
current = current.link;
count--;
//Method to return the info as a string.
//Postcondition: info as a String object is returned.
public String toString()
return current.info.toString();
} //end class LinkedListIterator
//Instance variables of the class LinkedListClass
protected LinkedListNode<T> first; //variable to store the
//address of the first
//node of the list
protected LinkedListNode<T> last; //variable to store the
//address of the last
//node of the list
protected int count; //variable to store the number of
//nodes in the list
//Default constructor
//Initializes the list to an empty state.
//Postcondition: first = null, last = null,
// count = 0
public LinkedListClass()
first = null;
last = null;
count = 0;
//Method to determine whether the list is empty.
//Postcondition: Returns true if the list is empty;
// false otherwise.
public boolean isEmptyList()
return (first == null);
//Method to initialize the list to an empty state.
//Postcondition: first = null, last = null,
// count = 0
public void initializeList()
first = null;
last = null;
count = 0;
//Method to output the data contained in each node.
public void print()
LinkedListNode<T> current; //variable to traverse
//the list
current = first; //set current so that it points to
//the first node
while (current != null) //while more data to print
System.out.print(current.info + " ");
current = current.link;
}//end print
//Method to return the number of nodes in the list.
//Postcondition: The value of count is returned.
public int length()
return count;
//Method to return a reference of the object containing
//the data of the first node of the list.
//Precondition: The list must exist and must not be empty.
//Postcondition: The reference of the object that
// contains the info of the first node
// is returned.
public T front()
return first.info;
//Method to return a reference of object containing
//the data of the last node of the list.
//Precondition: The list must exist and must not be empty.
//Postcondition: The reference of the object that
// contains the info of the last node
// is returned.
public T back()
return last.info;
//Returns a copy of objects data in store.
//This method clones only the references stored in
//each node of the list. The objects that the
//list nodes point to are not cloned.
public Object clone()
LinkedListClass<T> copy = null;
try
copy = (LinkedListClass<T>) super.clone();
catch (CloneNotSupportedException e)
return null;
//If the list is not empty clone each node of
//the list.
if (first != null)
//Clone the first node
copy.first = (LinkedListNode<T>) first.clone();
copy.last = copy.first;
LinkedListNode<T> current;
if (first != null)
current = first.link;
else
current = null;
//Clone the remaining nodes of the list
while (current != null)
copy.last.link =
(LinkedListNode<T>) current.clone();
copy.last = copy.last.link;
current = current.link;
return copy;
//Method to return an iterator of the list.
//Postcondition: An iterator is instantiated and
// returned.
public LinkedListIterator<T> iterator()
return new LinkedListIterator<T>();
//Method to determine whether searchItem is in
//the list.
//Postcondition: Returns true if searchItem is found
// in the list; false otherwise.
public abstract boolean search(T searchItem);
//Method to insert newItem in the list.
//Postcondition: first points to the new list
// and newItem is inserted at the
// beginning of the list. Also,
// last points to the last node and
// count is incremented by 1.
public abstract void insertFirst(T newItem);
//Method to insert newItem at the end of the list.
//Postcondition: first points to the new list and
// newItem is inserted at the end
// of the list. Also, last points to
// the last node and
// count is incremented by 1.
public abstract void insertLast(T newItem);
//Method to delete deleteItem from the list.
//Postcondition: If found, the node containing
// deleteItem is deleted from the
// list. Also, first points to the first
// node, last points to the last
// node of the updated list, and count
// is decremented by 1.
public abstract void deleteNode(T deleteItem);
public abstract void splitAt(LinkedListClass<T> secondList, T item);
}And this is the UnorderedLinked Class with the very last method the one being Im stuck on. The SplitAt Method.
public class UnorderedLinkedList<T> extends LinkedListClass<T>
//Default constructor
public UnorderedLinkedList()
super();
//Method to determine whether searchItem is in
//the list.
//Postcondition: Returns true if searchItem is found
// in the list; false otherwise.
public boolean search(T searchItem)
LinkedListNode<T> current; //variable to traverse
//the list
boolean found;
current = first; //set current to point to the first
//node in the list
found = false; //set found to false
while (current != null && !found) //search the list
if (current.info.equals(searchItem)) //item is found
found = true;
else
current = current.link; //make current point to
//the next node
return found;
//Method to insert newItem in the list.
//Postcondition: first points to the new list
// and newItem is inserted at the
// beginning of the list. Also,
// last points to the last node and
// count is incremented by 1.
public void insertFirst(T newItem)
LinkedListNode<T> newNode; //variable to create the
//new node
newNode =
new LinkedListNode<T>(newItem, first); //create and
//insert newNode before
//first
first = newNode; //make first point to the
//actual first node
if (last == null) //if the list was empty, newNode is
//also the last node in the list
last = newNode;
count++; //increment count
//Method to insert newItem at the end of the list.
//Postcondition: first points to the new list and
// newItem is inserted at the end
// of the list. Also, last points to
// the last node and
// count is incremented by 1.
public void insertLast(T newItem)
LinkedListNode newNode; //variable to create the
//new node
newNode =
new LinkedListNode(newItem, null); //create newNode
if (first == null) //if the list is empty, newNode is
//both the first and last node
first = newNode;
last = newNode;
else //if the list is not empty, insert
//newNode after last
last.link = newNode; //insert newNode after last
last = newNode; //set last to point to the
//actual last node
count++;
}//end insertLast
//Method to delete deleteItem from the list.
//Postcondition: If found, the node containing
// deleteItem is deleted from the
// list. Also, first points to the first
// node, last points to the last
// node of the updated list, and count
// is decremented by 1.
public void deleteNode(T deleteItem)
LinkedListNode<T> current; //variable to traverse
//the list
LinkedListNode<T> trailCurrent; //variable just
//before current
boolean found;
if ( first == null) //Case 1; the list is empty
System.err.println("Cannot delete from an empty "
+ "list.");
else
if (first.info.equals(deleteItem)) //Case 2
first = first.link;
if (first == null) //the list had only one node
last = null;
count--;
else //search the list for the given info
found = false;
trailCurrent = first; //set trailCurrent to
//point to the first node
current = first.link; //set current to point to
//the second node
while (current != null && !found)
if (current.info.equals(deleteItem))
found = true;
else
trailCurrent = current;
current = current.link;
}//end while
if (found) //Case 3; if found, delete the node
count--;
trailCurrent.link = current.link;
if (last == current) //node to be deleted
//was the last node
last = trailCurrent; //update the value
//of last
else
System.out.println("Item to be deleted is "
+ "not in the list.");
}//end else
}//end else
}//end deleteNode
public void splitAt(LinkedListClass<T> secondList, T item)
LinkedListNode<T> current;
LinkedListNode<T> trailCurrent;
int i;
boolean found;
if (first==null)
System.out.println("Empty.");
first=null;
last=null;
count--;
count=0;
else
current=first;
found=false;
i=1;
while(current !=null &&!found)
if(current.info.equals(item))
found= true;
else
trailCurrent=first;
current=first;
i++;
if(found)
if(first==current)
first.link=first;
last.link=last;
count--;
count=0;
else
first.link=current;
last.link=last;
last=null;
count = count- i+1;
count = i-1;
} else {
System.out.println("Item to be split at is "
+ "not in the list.");
first=null;
last=null;
count=0;
Any help or just advice would be fine. Im not the best at Java, better at VB. Am completely stumped! Thanks so much!
Similar Messages
-
Can someone help with splitting a Linked List.??
Any help would be awesome!!!
My code just will not work!! Any help would be appreciated! My problem is in the last method SplitAt. These are the conditions set and my code:
Splitting a Linked List at a Given Node, into Two Sublists
a. Add the following as an abstract method to the class
LinkedListClass:
public void splitAt (LinkedListClass<T> secondList, T item);
//This method splits the list at the node with the info item into two sublists.
//Precondition: The list must exist.
//Postcondition: first and last point to the first and last nodes of the first sublist,
// respectively. secondList.first and secondList.last point to the first
// and last nodes of the second sublist.
Consider the following statements:
UnorderedLinkedList<Integer> myList;
UnorderedLinkedList<Integer> otherList;
Suppose myList points to the list with the elements 34, 65, 18, 39, 27, 89, and 12 (in this order). The statement
myList.splitAt(otherList, 18);
splits myList into two sublists: myList points to the list with elements 34 and 65, and otherList points to the sublist with elements 18, 39, 27, 89, and 12.
b. Provide the definition of the method splitAt in the class UnorderedLinkedList. Also write a program to test your method.
public class UnorderedLinkedList<T> extends LinkedListClass<T>
//Default constructor
public UnorderedLinkedList()
super();
//Method to determine whether searchItem is in
//the list.
//Postcondition: Returns true if searchItem is found
// in the list; false otherwise.
public boolean search(T searchItem)
LinkedListNode<T> current; //variable to traverse
//the list
boolean found;
current = first; //set current to point to the first
//node in the list
found = false; //set found to false
while (current != null && !found) //search the list
if (current.info.equals(searchItem)) //item is found
found = true;
else
current = current.link; //make current point to
//the next node
return found;
//Method to insert newItem in the list.
//Postcondition: first points to the new list
// and newItem is inserted at the
// beginning of the list. Also,
// last points to the last node and
// count is incremented by 1.
public void insertFirst(T newItem)
LinkedListNode<T> newNode; //variable to create the
//new node
newNode =
new LinkedListNode<T>(newItem, first); //create and
//insert newNode before
//first
first = newNode; //make first point to the
//actual first node
if (last == null) //if the list was empty, newNode is
//also the last node in the list
last = newNode;
count++; //increment count
//Method to insert newItem at the end of the list.
//Postcondition: first points to the new list and
// newItem is inserted at the end
// of the list. Also, last points to
// the last node and
// count is incremented by 1.
public void insertLast(T newItem)
LinkedListNode newNode; //variable to create the
//new node
newNode =
new LinkedListNode(newItem, null); //create newNode
if (first == null) //if the list is empty, newNode is
//both the first and last node
first = newNode;
last = newNode;
else //if the list is not empty, insert
//newNode after last
last.link = newNode; //insert newNode after last
last = newNode; //set last to point to the
//actual last node
count++;
}//end insertLast
//Method to delete deleteItem from the list.
//Postcondition: If found, the node containing
// deleteItem is deleted from the
// list. Also, first points to the first
// node, last points to the last
// node of the updated list, and count
// is decremented by 1.
public void deleteNode(T deleteItem)
LinkedListNode<T> current; //variable to traverse
//the list
LinkedListNode<T> trailCurrent; //variable just
//before current
boolean found;
if ( first == null) //Case 1; the list is empty
System.err.println("Cannot delete from an empty "
+ "list.");
else
if (first.info.equals(deleteItem)) //Case 2
first = first.link;
if (first == null) //the list had only one node
last = null;
count--;
else //search the list for the given info
found = false;
trailCurrent = first; //set trailCurrent to
//point to the first node
current = first.link; //set current to point to
//the second node
while (current != null && !found)
if (current.info.equals(deleteItem))
found = true;
else
trailCurrent = current;
current = current.link;
}//end while
if (found) //Case 3; if found, delete the node
count--;
trailCurrent.link = current.link;
if (last == current) //node to be deleted
//was the last node
last = trailCurrent; //update the value
//of last
else
System.out.println("Item to be deleted is "
+ "not in the list.");
}//end else
}//end else
}//end deleteNode
public void splitAt(LinkedListClass<T> secondList, T item)
LinkedListNode<T> current;
LinkedListNode<T> trailCurrent;
int i;
boolean found;
if (first==null)
System.out.println("Empty.");
first=null;
last=null;
count--;
else
current=first;
found=false;
i=1;
while(current !=null &&!found)
if(current.info.equals(secondList))
found= true;
else
trailCurrent=current;
i++;
if(found)
if(first==current)
first=first;
last=last;
count=count;
count=0;
else
first=current;
last=last;
last=null;
count = count- i+1;
count = i-1;
else
System.out.println("Item to be split at is "
+ "not in the list.");
first=null;
last=null;
count=0;
}Edited by: romeAbides on Oct 10, 2008 1:24 PMI dont have a test program at all. The program is supposed to prompt for user input of numbers. (it does) Take the input and end at input of -999 (it does). Then it asks user where it wants to split list (it does). When I enter a number it does nothing after that. I am going to post updated code and see if that helps along with all the classes. Thanks!
This is the class to prompt:
import java.util.*;
public class Ch16_ProgEx6
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
UnorderedLinkedList<Integer> list
= new UnorderedLinkedList<Integer>();
UnorderedLinkedList<Integer> subList =
new UnorderedLinkedList<Integer>();
Integer num;
System.out.println("Enter integers ending with -999.");
num = console.nextInt();
while (num != -999)
list.insertLast(num);
num = console.nextInt();
System.out.println();
System.out.println("list: ");
list.print();
System.out.println();
System.out.println("Length of list: " + list.length());
System.out.print("Enter the number at which to split list: ");
num = console.nextInt();
list.splitAt(subList, num);
System.out.println("Lists after splitting list");
System.out.print("list: ");
list.print();
System.out.println();
System.out.println("Length of list: " + list.length());
System.out.print("sublist: ");
subList.print();
System.out.println();
System.out.println("Length of sublist: " + subList.length());
}This is the ADT:
public interface LinkedListADT<T> extends Cloneable
public Object clone();
//Returns a copy of objects data in store.
//This method clones only the references stored in
//each node of the list. The objects that the
//list nodes point to are not cloned.
public boolean isEmptyList();
//Method to determine whether the list is empty.
//Postcondition: Returns true if the list is empty;
// false otherwise.
public void initializeList();
//Method to initialize the list to an empty state.
//Postcondition: The list is initialized to an empty
// state.
public void print();
//Method to output the data contained in each node.
public int length();
//Method to return the number of nodes in the list.
//Postcondition: The number of nodes in the list is
// returned.
public T front();
//Method to return a reference of the object containing
//the data of the first node of the list.
//Precondition: The list must exist and must not be empty.
//Postcondition: The reference of the object that
// contains the info of the first node
// is returned.
public T back();
//Method to return a reference of object containing
//the data of the last node of the list.
//Precondition: The list must exist and must not be empty.
//Postcondition: The reference of the object that
// contains the info of the last node
// is returned.
public boolean search(T searchItem);
//Method to determine whether searchItem is in the list.
//Postcondition: Returns true if searchItem is found
// in the list; false otherwise.
public void insertFirst(T newItem);
//Method to insert newItem in the list.
//Postcondition: newItem is inserted at the
// beginning of the list.
public void insertLast(T newItem);
//Method to insert newItem at the end of the list.
//Postcondition: newItem is inserted at the end
// of the list.
public void deleteNode(T deleteItem);
//Method to delete deleteItem from the list.
//Postcondition: If found, the node containing
// deleteItem is deleted from the
// list.
public void splitAt(LinkedListClass<T> secondList, T item);
}This is the linked list class:
import java.util.NoSuchElementException;
public abstract class LinkedListClass<T> implements LinkedListADT<T>
protected class LinkedListNode<T> implements Cloneable
public T info;
public LinkedListNode<T> link;
//Default constructor
//Postcondition: info = null; link = null;
public LinkedListNode()
info = null;
link = null;
//Constructor with parameters
//This method sets info pointing to the object to
//which elem points to and link is set to point to
//the object to which ptr points to.
//Postcondition: info = elem; link = ptr;
public LinkedListNode(T elem, LinkedListNode<T> ptr)
info = elem;
link = ptr;
//Returns a copy of objects data in store.
//This method clones only the references stored in
//the node. The objects that the nodes point to
//are not cloned.
public Object clone()
LinkedListNode<T> copy = null;
try
copy = (LinkedListNode<T>) super.clone();
catch (CloneNotSupportedException e)
return null;
return copy;
//Method to return the info as a string.
//Postcondition: info as a String object is
// returned.
public String toString()
return info.toString();
} //end class LinkedListNode
public class LinkedListIterator<T>
protected LinkedListNode<T> current; //variable to
//point to the
//current node in
//list
protected LinkedListNode<T> previous; //variable to
//point to the
//node before the
//current node
//Default constructor
//Sets current to point to the first node in the
//list and sets previous to null.
//Postcondition: current = first; previous = null;
public LinkedListIterator()
current = (LinkedListNode<T>) first;
previous = null;
//Method to reset the iterator to the first node
//in the list.
//Postcondition: current = first; previous = null;
public void reset()
current = (LinkedListNode<T>) first;
previous = null;
//Method to return a reference of the info of the
//current node in the list and to advance iterator
//to the next node.
//Postcondition: previous = current;
// current = current.link;
// A refrence of the current node
// is returned.
public T next()
if (!hasNext())
throw new NoSuchElementException();
LinkedListNode<T> temp = current;
previous = current;
current = current.link;
return temp.info;
//Method to determine whether there is a next
//element in the list.
//Postcondition: Returns true if there is a next
// node in the list; otherwise
// returns false.
public boolean hasNext()
return (current != null);
//Method to remove the node currently pointed to
//by the iterator.
//Postcondition: If iterator is not null, then the
// node that the iterator points to
// is removed. Otherwise the method
// throws NoSuchElementException.
public void remove()
if (current == null)
throw new NoSuchElementException();
if (current == first)
first = first.link;
current = (LinkedListNode<T>) first;
previous = null;
if (first == null)
last = null;
else
previous.link = current.link;
if (current == last)
last = first;
while (last.link != null)
last = last.link;
current = current.link;
count--;
//Method to return the info as a string.
//Postcondition: info as a String object is returned.
public String toString()
return current.info.toString();
} //end class LinkedListIterator
//Instance variables of the class LinkedListClass
protected LinkedListNode<T> first; //variable to store the
//address of the first
//node of the list
protected LinkedListNode<T> last; //variable to store the
//address of the last
//node of the list
protected int count; //variable to store the number of
//nodes in the list
//Default constructor
//Initializes the list to an empty state.
//Postcondition: first = null, last = null,
// count = 0
public LinkedListClass()
first = null;
last = null;
count = 0;
//Method to determine whether the list is empty.
//Postcondition: Returns true if the list is empty;
// false otherwise.
public boolean isEmptyList()
return (first == null);
//Method to initialize the list to an empty state.
//Postcondition: first = null, last = null,
// count = 0
public void initializeList()
first = null;
last = null;
count = 0;
//Method to output the data contained in each node.
public void print()
LinkedListNode<T> current; //variable to traverse
//the list
current = first; //set current so that it points to
//the first node
while (current != null) //while more data to print
System.out.print(current.info + " ");
current = current.link;
}//end print
//Method to return the number of nodes in the list.
//Postcondition: The value of count is returned.
public int length()
return count;
//Method to return a reference of the object containing
//the data of the first node of the list.
//Precondition: The list must exist and must not be empty.
//Postcondition: The reference of the object that
// contains the info of the first node
// is returned.
public T front()
return first.info;
//Method to return a reference of object containing
//the data of the last node of the list.
//Precondition: The list must exist and must not be empty.
//Postcondition: The reference of the object that
// contains the info of the last node
// is returned.
public T back()
return last.info;
//Returns a copy of objects data in store.
//This method clones only the references stored in
//each node of the list. The objects that the
//list nodes point to are not cloned.
public Object clone()
LinkedListClass<T> copy = null;
try
copy = (LinkedListClass<T>) super.clone();
catch (CloneNotSupportedException e)
return null;
//If the list is not empty clone each node of
//the list.
if (first != null)
//Clone the first node
copy.first = (LinkedListNode<T>) first.clone();
copy.last = copy.first;
LinkedListNode<T> current;
if (first != null)
current = first.link;
else
current = null;
//Clone the remaining nodes of the list
while (current != null)
copy.last.link =
(LinkedListNode<T>) current.clone();
copy.last = copy.last.link;
current = current.link;
return copy;
//Method to return an iterator of the list.
//Postcondition: An iterator is instantiated and
// returned.
public LinkedListIterator<T> iterator()
return new LinkedListIterator<T>();
//Method to determine whether searchItem is in
//the list.
//Postcondition: Returns true if searchItem is found
// in the list; false otherwise.
public abstract boolean search(T searchItem);
//Method to insert newItem in the list.
//Postcondition: first points to the new list
// and newItem is inserted at the
// beginning of the list. Also,
// last points to the last node and
// count is incremented by 1.
public abstract void insertFirst(T newItem);
//Method to insert newItem at the end of the list.
//Postcondition: first points to the new list and
// newItem is inserted at the end
// of the list. Also, last points to
// the last node and
// count is incremented by 1.
public abstract void insertLast(T newItem);
//Method to delete deleteItem from the list.
//Postcondition: If found, the node containing
// deleteItem is deleted from the
// list. Also, first points to the first
// node, last points to the last
// node of the updated list, and count
// is decremented by 1.
public abstract void deleteNode(T deleteItem);
public abstract void splitAt(LinkedListClass<T> secondList, T item);
}And this is the UnorderedLinked Class with the very last method the one being Im stuck on. The SplitAt Method.
public class UnorderedLinkedList<T> extends LinkedListClass<T>
//Default constructor
public UnorderedLinkedList()
super();
//Method to determine whether searchItem is in
//the list.
//Postcondition: Returns true if searchItem is found
// in the list; false otherwise.
public boolean search(T searchItem)
LinkedListNode<T> current; //variable to traverse
//the list
boolean found;
current = first; //set current to point to the first
//node in the list
found = false; //set found to false
while (current != null && !found) //search the list
if (current.info.equals(searchItem)) //item is found
found = true;
else
current = current.link; //make current point to
//the next node
return found;
//Method to insert newItem in the list.
//Postcondition: first points to the new list
// and newItem is inserted at the
// beginning of the list. Also,
// last points to the last node and
// count is incremented by 1.
public void insertFirst(T newItem)
LinkedListNode<T> newNode; //variable to create the
//new node
newNode =
new LinkedListNode<T>(newItem, first); //create and
//insert newNode before
//first
first = newNode; //make first point to the
//actual first node
if (last == null) //if the list was empty, newNode is
//also the last node in the list
last = newNode;
count++; //increment count
//Method to insert newItem at the end of the list.
//Postcondition: first points to the new list and
// newItem is inserted at the end
// of the list. Also, last points to
// the last node and
// count is incremented by 1.
public void insertLast(T newItem)
LinkedListNode newNode; //variable to create the
//new node
newNode =
new LinkedListNode(newItem, null); //create newNode
if (first == null) //if the list is empty, newNode is
//both the first and last node
first = newNode;
last = newNode;
else //if the list is not empty, insert
//newNode after last
last.link = newNode; //insert newNode after last
last = newNode; //set last to point to the
//actual last node
count++;
}//end insertLast
//Method to delete deleteItem from the list.
//Postcondition: If found, the node containing
// deleteItem is deleted from the
// list. Also, first points to the first
// node, last points to the last
// node of the updated list, and count
// is decremented by 1.
public void deleteNode(T deleteItem)
LinkedListNode<T> current; //variable to traverse
//the list
LinkedListNode<T> trailCurrent; //variable just
//before current
boolean found;
if ( first == null) //Case 1; the list is empty
System.err.println("Cannot delete from an empty "
+ "list.");
else
if (first.info.equals(deleteItem)) //Case 2
first = first.link;
if (first == null) //the list had only one node
last = null;
count--;
else //search the list for the given info
found = false;
trailCurrent = first; //set trailCurrent to
//point to the first node
current = first.link; //set current to point to
//the second node
while (current != null && !found)
if (current.info.equals(deleteItem))
found = true;
else
trailCurrent = current;
current = current.link;
}//end while
if (found) //Case 3; if found, delete the node
count--;
trailCurrent.link = current.link;
if (last == current) //node to be deleted
//was the last node
last = trailCurrent; //update the value
//of last
else
System.out.println("Item to be deleted is "
+ "not in the list.");
}//end else
}//end else
}//end deleteNode
public void splitAt(LinkedListClass<T> secondList, T item)
LinkedListNode<T> current;
LinkedListNode<T> trailCurrent;
int i;
boolean found;
if (first==null)
System.out.println("Empty.");
first=null;
last=null;
count--;
count=0;
else
current=first;
found=false;
i=1;
while(current !=null &&!found)
if(current.info.equals(item))
found= true;
else
trailCurrent=first;
current=first;
i++;
if(found)
if(first==current)
first.link=first;
last.link=last;
count--;
count=0;
else
first.link=current;
last.link=last;
last=null;
count = count- i+1;
count = i-1;
} else {
System.out.println("Item to be split at is "
+ "not in the list.");
first=null;
last=null;
count=0;
Any help or just advice would be fine. Im not the best at Java, better at VB. Am completely stumped! Thanks so much! -
How to SPLIT ONE STEREO TRACK'S L & R CHANNELS INTO TWO MONO CHANNELS
Does anyone know if this is possible: How to SPLIT ONE STEREO TRACK'S L & R CHANNELS INTO TWO MONO CHANNELS? There's got to be a way, but I just can't find out how.
I recorded a podcast -- me and a guest, with each mic going to its own mono channel. When I opened it in Audition it mixed them into one stereo channel.
Thanks in advance for any help.
Best,
ShawnYou're a big help! Thanks very much. Simple yet I must be going blind because I didn't see that in the menu.
Take care and THANKS AGAIN.
Shawn -
Alphabetically ordering a Linked List
Would anyone please be able to give me help in ordering a linked list alphabetically. I'm new to java so please be gentle.
Many thanks in advance.I've just tried that but it gave me errors on trying to compile it:
.\List.java:91: Incompatible type for method. Explicit cast needed to convert List to java.util.List.
Collections.sort(leftList);
^
.\List.java:92: Incompatible type for method. Explicit cast needed to convert List to java.util.List.
Collections.sort(rightList);
^
2 errors
I'll post my coding below to see if you can help me out. Thanks a lot.
import java.util.LinkedList;
import java.util.Collections;
class ListNode {
// package access data so class List can access it directly
char data;
ListNode next;
// Constructor: Create a ListNode that refers to Object o.
ListNode( char c ) { this( c, null ); }
// Constructor: Create a ListNode that refers to Object o and
// to the next ListNode in the List.
ListNode( char c, ListNode nextNode )
data = c; // this node refers to Object o
next = nextNode; // set next to refer to next
// Return a reference to the Object in this node
char getChar() { return data; }
// Return the next node
ListNode getNext() { return next; }
// Class List definition
public class List {
private ListNode firstNode, current;
private ListNode lastNode;
private String name; // String like "list" used in printing
// Constructor: Construct an empty List with s as the name
public List( String s )
name = s;
firstNode = lastNode = null;
// Constructor: Construct an empty List with
// "list" as the name
public List() { this( "list" ); }
public synchronized boolean isEmpty()
{ return firstNode == null; }
public synchronized void insertAtBack( char insertItem )
if ( isEmpty() )
firstNode = lastNode = new ListNode( insertItem );
else
lastNode = lastNode.next = new ListNode( insertItem );
print();
// System.out.println(insertItem);
// public char getText(){
// return current.data;
// Output the List contents
public synchronized void print()
current = firstNode;
while ( current != null ) {
System.out.print(current.data);
current = current.next;
System.out.println( "\n" );
// method to split the linked list
public synchronized void splitList(){
System.out.println("splitList");
ListNode present = firstNode;
List leftList = new List(); // create the left list
List rightList = new List(); // create the right list
try{
while (present != null) {
leftList.insertAtBack(present.data);
System.out.println("left " +present.data);
present = present.next; // skips 1 node
rightList.insertAtBack(present.data);
System.out.println("right " +present.data);
present = present.next; // skips 1 node
Collections.sort(leftList);
Collections.sort(rightList);
catch(NullPointerException e){ -
Hey,
I am having trouble understanding the Linked List implementation code given under the Node Operations part of this pdf.
http://www.cs.berkeley.edu/~jrs/61b/lec/07.pdf
public ListNode(int item, ListNode next) {
this.item = item;
this.next = next;
public ListNode(int item) {
this(item, null);
ListNode l1 = new ListNode(7, new ListNode(0, new ListNode(6)));
I understand the earlier implementation, but this one has me confused. Would someone please go through/explain the flow of this implementation with me?
ThanksWell the code is pretty self explanitory.
a ListNode class that has two fields. an int field item, and a ListNode field next.
so when you create a ListNode object you can do so by one of two means passing one parameter or passing two parameters.
if you pass one parameter then you have a ListNode which has an int say 1 and a ListNode object who's value is null.
if you pass two parameters then you have a ListNode which has an int say 2 and a ListNode object who's value is the ListNode you pass to it.
ex ListNode myNode = ListNode(1,new ListNode(2));
so myNode now has an integer 1 and a reference to another ListNode which has an integer value of 2 and a reference to a null ListNode.
hope this helps. -
After Delete in Linked list...unable to display the linked list
Hi...i know that there is an implementation of the class Linked Link but i am required to show how the linked list works in this case for my project...please help...
Yes..I tried to delete some objects in a linked list but after that i am not able to display the objects that were already in the linked list properly and instead it throws an NullPointerException.
Below shows the relevant coding for deleting and listing the linked list...
public Node remove(Comparator comparer) throws Exception {
boolean found = false;
Node prevnode = head; //the node before the nextnode
Node deletedNode = null; //node deleted...
//get next node and apply removal criteria
for(Node nextnode = head.getNextNode(); nextnode != null; nextnode = nextnode.getNextNode()) {
if(comparer.equals(nextnode)) {
found = true;
//remove the next node from the list and return it
prevnode.setNextNode(nextnode.getNextNode());
nextnode.setNextNode(null);
deletedNode = nextnode;
count = count - 1;
break;
if (found) return deletedNode;
else throw new Exception ("Not found !!!");
public Object[] list() {
//code to gather information into object array
Node node;
Object[] nodes = new Object[count];
node = head.getNextNode();
for (int i=0; i<count; i++) {
nodes[i] = node.getInformation(); // this is the line that cause runtime error after deleting...but before deleting, it works without problem.
node = node.getNextNode();
return nodes;
}Please help me in figuring out what went wrong with that line...so far i really can't see any problem with it but it still throws a NullPointerException
ThanksOK -- I've had a cup and my systems are coming back on line...
The problem looks to be the way that you are handling the pointer to the previous node in your deletion code. Essentially, that is not getting incremented along with the nextNode -- it is always pointing to head. So when you find the node to delete then the line
prevnode.setNextNode(nextnode.getNextNode());will set the nextNode for head to be null in certain situations (like if you are removing the tail, for instance).
Then when you try to print out the list, the first call you make is
node = head.getNextNode();Which has been set to null, so you get an NPE when you try to access the information.
Nothing like my favorite alkaloid to help things along on a Monday morning...
- N -
Putting a class of objects in a Linked List?
Hi,
I copied a program from a book and I want to edit it and put studentRecord class in the Linked List. I've tried to play about with datum, but everything I try doesn't work. Can someone help me out? How could I put studentRecord in the LinkedList?
import java.io.*;
class IO
static BufferedReader keyboard = new
BufferedReader(new InputStreamReader(System.in));
static PrintWriter screen = new PrintWriter(System.out, true);
class studentRecord
private String name;
private int IDNumber;
class LinkedList
class Node
protected Object datum;
protected Node link;
public Node() {}
public Node(Object item, Node pointer)
datum = item;
link = pointer;
private Node head;
private Node tail;
private Node temporary;
private int nodeCount = 0;
//constructor
public LinkedList()
head = null;
tail = null;
temporary = null;
//method to insert an object into the linked list
public void insert(Object datum)
if (head == null) // list empty
head = new Node(datum, head);
tail = head;
else
temporary = new Node(datum, temporary);
tail.link = temporary;
tail = temporary;
temporary = null;
nodeCount++;
Full program can be found: http://dil3mma.tripod.com/LinkedList.txt
Thanks in advance.Hi jverd,
Thanks for replying. I've tried to change the program liked you said but there is 1 error I can't seem to fix(Im sure there are more tho). The error is "cannot resolve symbol" I typed in caps the line it happens on so it's easy to see. Any idea what it could be? Is it cause I'm comparing a String with Object?
import java.io.*;
class IO
static BufferedReader keyboard = new
BufferedReader(new InputStreamReader(System.in));
static PrintWriter screen = new PrintWriter(System.out, true);
class sRecord
private String name;
private int IDNumber;
class LinkedList
class Node
protected sRecord datum;
protected Node link;
public Node() {}
public Node(sRecord item, Node pointer)
datum = item;
link = pointer;
private Node head;
private Node tail;
private Node temporary;
private int nodeCount = 0;
//constructor
public LinkedList()
head = null;
tail = null;
temporary = null;
//method to insert an object into the linked list
public void insert(sRecord datum)
if (head == null) // list empty
head = new Node(datum, head);
tail = head;
else
temporary = new Node(datum, temporary);
tail.link = temporary;
tail = temporary;
temporary = null;
nodeCount++;
//method to delete an object from the linked list
public boolean delete(Object scrap)
Node previous = head;
//for every node in the linked list
for (Node current = head; current != null; current = current.link)
//node to be deleted is at the head of the list
if (current.datum.equals(scrap) && previous == current)
head = current.link;
if (head == null) tail = null;
nodeCount--;
return true;
//node to be deleted is after the first node and before the last
else if (current.datum.equals(scrap) && (current.link != null))
previous.link = current.link;
nodeCount--;
return true;
//node to be deleted is at the ned of list
else if (current.datum.equals(scrap) && (current.link == null))
tail = previous;
previous.link = null;
nodeCount--;
return true;
previous = current;
return false;
//method to display the contents of a linked list
public void displayList()
Node temporary = head;
if (head == null)
IO.screen.println("linked list is empty");
return;
while (temporary != null)
IO.screen.println(temporary.datum);
temporary = temporary.link;
//method to return true if the linked list is empty
public boolean isEmpty()
return (nodeCount == 0);
//method to return the number of nodes in the linked list
public int nodes()
return nodeCount;
//method to display a menu to insert data into the linked list
static private char menu()
char response = '\u0000';
IO.screen.println("Do you want to ");
IO.screen.print("nsert, [D]elete, [L]ist, [E]xit? ");
IO.screen.flush();
boolean done=false;
do
try
String data = IO.keyboard.readLine();
response = Character.toUpperCase(data.charAt(0));
done = true;
catch (Exception e)
IO.screen.println("Please input a single character I, D, L or E");
} while (! done);
return response;
static public void main(String[] args) throws IOException
LinkedList list = new LinkedList();
String datum;
char choice;
//get information from menu
choice = menu();
for (;;)
//Menu
switch (choice)
case 'I' :
IO.screen.println("type quit to finish input");
IO.screen.print("Enter a word ");
IO.screen.flush();
datum = IO.keyboard.readLine();
while (! datum.equals("quit"))
THE ERROR HAPPENS HERE ON THIS LINE list.insert(datum.name);
IO.screen.print("Enter another word");
IO.screen.flush();
datum = IO.keyboard.readLine();
break;
case 'D' :
//if list is empty deletion not possible
if (list.isEmpty())
IO.screen.println("linked list is empty");
break;
IO.screen.println("type quit to finish input");
IO.screen.print("Delete? ");
IO.screen.flush();
datum = IO.keyboard.readLine();
while (! datum.equals("quit"))
if (list.delete(datum))
IO.screen.println(datum+" was scrapped!");
//if list is empty deletion is not possible
if (list.isEmpty())
IO.screen.println("linked list is empty");
break;
IO.screen.print("Delete? ");
IO.screen.flush();
datum = IO.keyboard.readLine();
break;
case 'L' :
list.displayList();
IO.screen.println("number of nodes " + list.nodes());
break;
case 'E' : System.exit(0);
//get information from menu
choice = menu(); -
Anyone help me please~ many thanks! C++ linked list
I've written a Microsoft C++ code, using a linked list to store the result which is sent by a device.
The head node and tail node of linked list is put into a class, and all methods are set to 'static' to manipulate the data inside the linked list. So that different thread can access to it.
At first, everything runs ok in native environment,( i compile it as a .exe file)....
However, when I export it into DLL and run inside java code using JNI. The linked list was gone (head node & tail node lost). It seems that JVM try to re-initialize the head node everytime I invoke those method.
Hence, I modify the class which handle the link list, set all its methods into non-static, and define a global variable. Yet, another problem came out... Acess Violation error... it seems again the adress(pointer) of head node can't be modified...
Is there any other way to solve this problem?? I mean, I want the head node remains valid for each time of java method is called.Too vague.
If you could show us some relevant Java and JNI C++
code.
Please paste your code between code tags exactly like
this:
your codeYou may read the [url
http://forum.java.sun.com/help.jspa?sec=formatting]For
matting tips for more information.Here you are:
this is the header definition of the linked list handler, all functions are set to be non-static
typedef struct DeviceLinkList{
char *deviceNumber;//device of monitor device
int result;
DeviceLinkList *nextNode;
DeviceLinkList *prevNode;
} DeviceLinkList;
class DeviceListHandler
public:
DeviceLinkList *headNode = NULL;
DeviceLinkList *tailNode = NULL; //Moving to last of the entry
void addNode(char *device); //add monitor device
void deleteNode(char *device); //remove after device is stop monitorred
void printAll();
void setResult(char *device);
private:
DeviceLinkList *searchNode(char *device);
};Here is the implementation of my code in function 'addNode':
void DeviceListHandler::addNode(char *device)
printf("Creating Link List.\n");
printf("Head is %d\n" ,headNode);
if(headNode != NULL) //create new node from empty --> Access Violation Exception start from here
DeviceLinkList *temp = new DeviceLinkList;
temp->deviceNumber = device;
temp->nextNode = NULL;
temp->prevNode = tailNode;
tailNode->nextNode = temp;
tailNode = temp; //move tailNode point to the last entry
printf("Connecting to Tail Node done\n");
else
DeviceLinkList *temp = new DeviceLinkList;
printf("Creating Head\n");
temp = new DeviceLinkList;
temp->deviceNumber = device;
temp->nextNode = NULL;
temp->prevNode = NULL;
printf(".....DONE...!!!\n");
headNode = temp;
tailNode = headNode;
printf("Finish Head-Tail Node creation\n");
printf("Creation Done\n");
}This is the one of function which export to JNI:
JNIEXPORT void JNICALL Java_PBXdll_monitorStart (JNIEnv * env, jobject obj, jstring callingdevice)
char device[MAX_CstaDialingNumber];
strcpy(device,env->GetStringUTFChars(callingdevice, 0));
printf("Monitoring device: %s\n", device);
startMonitor(device);
deviceList -> addNode(device); // deviceList is the global variable
}so...when i call the method monitorStart in java... it terminated abnormally with a Access Violation Exception.....the linked list can't be created. -
Hi Guys,
I am trying to create a single linked list with one node pointing to the other. Then I have to create a method that displays the contents of the nodes. This method must take the head of the linked list as a parameter.
I have created a class called node to store the data of each node created: This is the class;
public class Node {
String data;
Node next;
public Node(String data) {
setData(data);
setNext(null);
} // Constructor
public void setData(String data) {
this.data = data;
public void setNext(Node next) {
this.next = next;
public String getData() {
return data;
public Node getNext() {
return next;
public String toString() {
if(data == null)
return "Node: null";
else
return "Node: " + data.toString();
}The second class is LinkedList which initialises each node and creates the linked list.
public class LinkedList {
private Node head;
public LinkedList() {
setHead(null);
} // constructor
private void setHead(Node head) {
this.head = head;
} // setHead
private Node getHead() {
return head;
} // getHead
public void add(String data) {
if(getHead() == null){
Node temp = new Node(data);
temp.setNext(getHead());
setHead(temp);
else
add(getHead(), data);
} // add
public static void main (String args[]){
Node n1 = new Node();
n1.setData("Jane");
if (getHead() == null){
setHead(n1);
}else{
System.out.println ("No initialisation of Linked List");
n1.setNext(n2);
Node n2 = new Node();
n2.setNext(n3);
n2.setData("Maria");
Node n3 = new Node();
n3.setNext(n4);
n3.setData("Paul");
Node n4 = new Node();
n4.setData("Charlene");
}Am I on the right track? And how can I create the method to display all the nodes which takes the head of the list as a parameter only?
Thanks a lotdoobybug wrote:
The code I posted compiled.Then pls fix me errors:
LinkedList.java:24: add(java.lang.String) in LinkedList cannot be applied to (Node,java.lang.String)
add(getHead(), data);
^
LinkedList.java:29: cannot find symbol
symbol : constructor Node()
location: class Node
Node n1 = new Node();
^
LinkedList.java:31: non-static method getHead() cannot be referenced from a static context
if (getHead() == null){
^
LinkedList.java:32: non-static method setHead(Node) cannot be referenced from a static context
setHead(n1);
^
LinkedList.java:35: cannot find symbol
symbol : variable n2
location: class LinkedList
n1.setNext(n2);
^
LinkedList.java:36: cannot find symbol
symbol : constructor Node()
location: class Node
Node n2 = new Node();
^
\LinkedList.java:37: cannot find symbol
symbol : variable n3
location: class LinkedList
n2.setNext(n3);
^
LinkedList.java:39: cannot find symbol
symbol : constructor Node()
location: class Node
Node n3 = new Node();
^
LinkedList.java:40: cannot find symbol
symbol : variable n4
location: class LinkedList
n3.setNext(n4);
^
LinkedList.java:42: cannot find symbol
symbol : constructor Node()
location: class Node
Node n4 = new Node();
^
10 errors -
WPC - highlighting the link of the current page in the link list
Hi,
is there any way to highlight a link in my linklist if it's the link to the page i am currently visiting?
That would make it possible for me to customize the link list form and change it into some kind of "tab"-list form where the current tab is highlighted.
A solution via xsl would be fantastic.
Thanks for your support.
SebastianYou can submit ideas here - http://hendrix.mozilla.org/
The [https://addons.mozilla.org/firefox/addon/3880/ Add Bookmark Here ²] extension does what you want. -
Method to remove a given node from the list?
Anybody know how to do it?
import java.util.Iterator;
import java.util.HashSet;
import java.util.Set;
* A doubly linked list as introduced in lecture 6 in IN2002. Template for
* coursework 2a in 2006.
public class DLList implements Iterable {
* Inner class for doubly linked list nodes.
class DLNode {
Object info; // the data element
DLNode next; // the next node
DLNode prev; // the previous node
DLNode(Object argInfo) {
info = argInfo;
private DLNode head, tail;
private int count;
* Appends an object at the tail of this list.
* @param argOb The object to append.
public void appendAtTail(Object argOb) {
DLNode node = new DLNode(argOb); // new node
if (tail == null) { // empty list
tail = node; // set the tail
head = tail; // and head
} else { // non-empty list
tail.next = node; // connect the
node.prev = tail; // new node
tail = node; // set the tail
count++; // udpate count
* Deletes the given node maintaining the list structure.
* @param node The node to delete, must be in the list.
private void delete(DLNode node) {
..............................??? -
Recursively Finding a Node in a Linked List
I'm trying to find a node recursively in this linked list but keep coming up with an error message - can anyone tell me what is wrong?
public boolean find (Object obj)
DonorNode node = new DonorNode(obj);
DonorNode current = list;
if (don.equals(current))
return true;
else
return find(current.next);
}Please post within code tags (button above the message box).
Without more information it's hard to say.
What is list?
What is don?
If you don't mind me pointing out:
A method named find conventionally returns some object it is searching for or null if not found.
What you have (by that I mean a method returning boolean) is generally named contains (or some other obvious predicate name).
That being said, if I assume that DonorNodes contain some Object and have getter functions to access those; and that list is a DonorNode representing the head of the list, try something like:public boolean contains(Object o) {
return contains(o, list);
private boolean contains(Object o, DonorNode n) {
if (n.getObject() == o)
return true;
if (n.getNext() == null)
return false;
return contains(o, n.getNext());
}Although keep in mind that comparing two Objects using '==' will result in reference only comparison. If you need some other form of comparison you might consider using the equals method (make sure you then implement it in all potentially contained classes) or even narrowing the accepted argument to classes that implement the Comparable interface.
Hope this helps. -
Linked List - deleeting nodes - HELP!
How do I delete all occurences of the nodes with the same parameters in the linked list ?
example:
Node1-> Node2 ->Node3->Node4->Node5
Node1, Node4, and Node5 have the same String value, how do I delete them in one method without breaking the linked list ?
thanksHi,
You have iterate thru the linked list remove one by one. Also have look at other collection classes like HashSet or HashMap for fast retrieval. -
Hello,
I have a double linked list where I want to change one node to another and change its references at the same time.
The nodes are not together i.e. they do not appear in the list consectutively.
I need to swap like B and D - I have managed to do swaps like A and B, and C and D (that took a while).
Is this logic correct (I am using temporary nodes):
if(f1 != (f2 - 1))
Object temp = object1;
Object temp2 = object2;
object1.getPrevious().setNext(object2);
object2.getNext().setPrevious(object1);
object1.getNext().setPrevious(object2);
object2.getPrevious().setNext(object1);
object1.setPrevious(temp2.getPrevious());
object1.setNext(temp2.getNext());
object2.setPrevious(temp.getPrevious());
object2.setNext(temp.getNext());
If this logic is not correct then please only give hints as to why.
CheersHello,
I have a double linked list where I want to change
one node to another and change its references at the
same time.
The nodes are not together i.e. they do not appear in
the list consectutively.
I need to swap like B and D - I have managed to do
swaps like A and B, and C and D (that took a while).
Is this logic correct (I am using temporary nodes):
if(f1 != (f2 - 1))
Object temp = object1;
Object temp2 = object2;
object1.getPrevious().setNext(object2);
object2.getNext().setPrevious(object1);
object1.getNext().setPrevious(object2);
object2.getPrevious().setNext(object1);
object1.setPrevious(temp2.getPrevious());
object1.setNext(temp2.getNext());
object2.setPrevious(temp.getPrevious());
object2.setNext(temp.getNext());
If this logic is not correct then please only give
hints as to why.
CheersI didn't check your logic, but I think that there are errors in it since I saw these lines:
object1.setPrevious(temp2.getPrevious());
object1.setNext(temp2.getNext());
object2.setPrevious(temp.getPrevious());
object2.setNext(temp.getNext()); temp and temp2 are not copies of object1 and object2. They are references to the same object, so when you do e.g. object1.getPrevious().setNext() you also change previous->next for temp.
temp == object1
temp2 == object2
Kaj -
Hi,
In a lecture a couple of weeks ago, we began the topic of reference-based lists. I copied the attached
code off the board. I'm now trying to utilize the code by creating a public class Node. However, the constructors don't seem to make much sense. I was too busy writing down the information to pay much attention at the time. My book doesn't seem to address this...
1) in the first constructor: item = null; I'm declaring item initially as an integer, but the constructor is trying to attach a null to item. I think the intent is to create a node that initially has both info and link as nulls.
2) in the third constructor: link = Node; Is this possible? I'm not what this will do.
And finally, the second and third constructors are using the same name and parameter, so there is a conflict. I don't know how to resolve this.
Thanks in advance for any help...
aiki
public class Node {
public int info;
public Node link;
public Node(){
info = null;
link = null;
public Node (int data){
info = data;
link = null;
public Node (int data){
info = data;
link = Node;public class Node {
public int info;
public Node link;
public Node(){
// default constructor does nothing.
// Therefore info and link will get default values.
// For Objects this will be null
public Node (int data){
info = data;
// don't initialise link. See above
public Node (int data, Node node){
// I think you missed the second parameter
info = data;
link = node;
}
Maybe you are looking for
-
Windows 7 on imac 27 not waking up properly
Hi, I have an imac 27 , I've installed windows 7 on it. There is one bug that is persisting no matter what I do. The machine works all fine except on wake up from sleep it often(>70%) crashes. I have tried the following 1) installing windows 32 bit v
-
What does it take to get a response from someone?
I sent a direct message to MatthewS_vzw 5 days ago and haven't heard a word yet! Has anyone else had trouble getting a response when they posted a question?
-
Purchase Requisition number (current number) not seen correctly in OMI2
Hi All, I see purchase requisition number created for the last number in the number range defined for Purchase Req., but i do not see the last number in the "current number" area. What are the possible reason for this ? Regards, PSS Edited by: PSS on
-
ITUNES only sees ipod if plugged in at system bootup time
Anyone have and ideas? Up until 6:00PMish last night I was running ITUNES 4 without any problems. I had difficulty upgrading to version 6 awhile ago so I decided to stay on 4 for now. When I wanted to buy a song last night, the ITUNES store forced me
-
COPA Product wise profitability
Hi Sapians I have execute an order settlement and variance is successfully posted in COPA Value field VV002(Qty variance) In product wise profitability report. System shows as follows: Product Qty Sales value Cost @ Std price order Variance V