Linked list remove method???
hi i have made a remove method in a publication contaqiner class which links to the publicationmain.The problem is that when i run the program and try to delete a publication i get the message
"Exception in thread "main" java.lang.IndexOutOfBoundsException: Index:1, Size:1 at java.util.LinkedList.entry<LinkedList.java:348>
java.util.LinkedList.remove<LinkedList.java:338>
PublicationContainer.remove<publicationcontainer.java>
publicationmain.main<publicationmain.java>"
What does this mean?how do i fix it so my delete method workks?can ssomeone please show me in my code???thanxs
//this is in the publication container
public void remove(int PubID)
PubList.remove(PubID);
//this is in the publicationmain class
System.out.println ("Enter Publication ID:");
PubID = Keyboard.readInt();
pubdatabase.remove (PubID);
The remove(int index) method that you are calling will try and remove the item at the index you specify.
As the index starts at zero, if you want to remove the first element then you have to call remove(0). Calling remove(1) is beyound the possible indexes in the list, so you will get the exception thrown.
HTH
Chris
hi i have made a remove method in a publication
contaqiner class which links to the
publicationmain.The problem is that when i run the
program and try to delete a publication i get the
message
"Exception in thread "main"
java.lang.IndexOutOfBoundsException: Index:1, Size:1
at java.util.LinkedList.entry<LinkedList.java:348>
java.util.LinkedList.remove<LinkedList.java:338>
PublicationContainer.remove<publicationcontainer.java>
publicationmain.main<publicationmain.java>"
What does this mean?how do i fix it so my delete
method workks?can ssomeone please show me in my
code???thanxs
//this is in the publication container
public void remove(int PubID)
PubList.remove(PubID);
//this is in the publicationmain class
System.out.println ("Enter Publication ID:");
PubID = Keyboard.readInt();
pubdatabase.remove (PubID);
Similar Messages
-
nevermind...I figured it out
Message was edited by:
jpnGirlConsider the list 1, 3, 5, 7 and the numbers 3 and 5 are to swapped.
Your problem is that prev points to 3 and temp points to 5 and you have no pointer to 1. The problem is you need to change 1 to point to 5 not 3 but can't. I guess you are confusing yourself by using prev but it points to the current number not the previous one.
Too late!
Message was edited by:
flounder -
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. -
How to use methods when objects stored in a linked list?
Hi friend:
I stored a series of objects of certain class inside a linked list. When I get one of them out of the list, I want to use the instance method associated with this object. However, the complier only allow me to treat this object as general object, ( of Object Class), as a result I can't use instance methods which are associated with this object. Can someone tell me how to use the methods associated with the objects which are stored inside a linked list?
Here is my code:
import java.util.*;
public class QueueW
LinkedList qList;
public QueueW(Collection s) //Constructor of QuequW Class
qList = new LinkedList(s); //Declare an object linked list
public void addWaiting(WaitingList w)
boolean result = qList.isEmpty(); //true if list contains no elements
if (result)
qList.addFirst(w);
else
qList.add(w);
public int printCid()
Object d = qList.getFirst(); // the complier doesn't allow me to treat d as a object of waitingList class
int n = d.getCid(); // so I use "Object d"
return n; // yet object can't use getCid() method, so I got error in "int n = d.getCid()"
public void removeWaiting(WaitingList w)
qList.removeFirst();
class WaitingList
int cusmNo;
String cusmName;
int cid;
private static int id_count = 0;
/* constructor */
public WaitingList(int c, String cN)
cusmNo = c;
cusmName = cN;
cid = ++id_count;
public int getCid() //this is the method I want to use
return cid;Use casting. In other words, cat the object taken from the collection to the correct type and call your method.
HashMap map = /* ... */;
map.put(someKey, myObject);
((MyClass)(map.get(someKey)).myMethod();Chuck -
Problem with removing items from a linked list
Hello,
I have something weird going with my code. Below is the snippet
if (ParserDataList.isEmpty())
try {
Thread.sleep(10)
catch (InterruptedException e) {
else
data = ParserDataList.remove();
ParserDataList is declared as a LinkedList. Occasionally I receive the error on NoSuchElement on the remove. I put a try/catch around the remove and print out the value of ParserDataList.isEmpty which is always false. I am very confused on why if the linked list isn't empty I can't remove a data item. There are no other threads that remove data. Thank you in advance for any assistance on this problem.I am changing it from linked list to blocking queue however I do have a question about what I should use to poll the data? Instead of a remove should I use take which seemed to remove the first element and if there wasn't one wait until there was. I was trying to not have the threads blocked because I do need to stop them when a disconnect is sent from the main thread.
-
Remove element in linked list linked list
here's my codes
public class Student
private String name, matric;
public Student(){}
public Student( String name, String matric)
this.name = name;
this.matric = matric;
public String getName()
{ return name;}
public void setName(String name)
{ this.name = name;}
public String getMatric()
{ return matric;}
public void setMatric( String matric)
{ this.matric = matric;}
public String toString()
return "Name: " + name + ", Matric no: " + matric + "\n";
}// end student classthe link list class
public class LinkedList extends java.util.LinkedList
// instance variables - replace the example below with your own
private ListNode firstNode;
private ListNode lastNode;
private ListNode currNode;
private String name;
* Constructor for objects of class LinkedList
public LinkedList(String s)
name = s;
firstNode = lastNode = currNode = null;
public LinkedList() {this("list");}
public synchronized void insertAtFront(Object insertItem) {
if (isEmpty())
firstNode = lastNode = new ListNode(insertItem);
else
firstNode = new ListNode(insertItem, firstNode);
public synchronized void insertAtBack(Object insertItem) {
if (isEmpty())
firstNode = lastNode = new ListNode(insertItem);
else
lastNode = lastNode.next = new ListNode(insertItem);
public synchronized Object removeFromFront() throws EmptyListException {
Object removeItem = null;
if (isEmpty())
throw new EmptyListException(name);
removeItem = firstNode.data;
if (firstNode.equals(lastNode))
firstNode = lastNode = null;
else
firstNode = firstNode.next;
return removeItem;
public synchronized Object removeFromBack() throws EmptyListException {
Object removeItem = null;
if (isEmpty()) throw new EmptyListException(name);
removeItem = lastNode.data;
if (firstNode.equals(lastNode))
firstNode = lastNode = null;
else {
ListNode current = firstNode;
while (current.next != null)
current = current.next;
lastNode = current;
current.next = null;
return removeItem;
public synchronized boolean isEmpty()
{ return firstNode == null;}
public synchronized Object getFirst() {
if (isEmpty())
return null;
else {
currNode = firstNode;
return currNode.data;
public synchronized Object getNext() {
if (currNode != lastNode) {
currNode = currNode.next;
return currNode.data;
else
return null;
public synchronized String print() {
String out = "";
if (isEmpty()) {
out = "Empty "+ name;
out = "The "+ name+ " is:\n";
ListNode current = firstNode;
while (current != null) {
out += ""+ current.data.toString();
current = current.next;
return out;
public synchronized Object getLast() {
if (isEmpty())
return null;
else {
currNode = lastNode;
return currNode.data;
}// end LinkedListand the application class
import java.io.*;
import java.util.*;
import javax.swing.*;
public class StudentAppLL
public static void main(String[] args) throws IOException {
LinkedList std = new LinkedList();
BufferedReader br = new BufferedReader(new FileReader("studentIn.txt"));
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("studentOut.txt")));
String line = br.readLine();
while (line != null) {
StringTokenizer tk = new StringTokenizer(line);
while (tk.hasMoreTokens()) {
String n = tk.nextToken();
String m = tk.nextToken();
Student a = new Student(n, m);
std.insertAtFront(a);
line = br.readLine();
std.print();
System.out.print(std.getFirst());
Student data = (Student)std.getFirst();
String matric;
String nm = "Zaki";
while (data != null) {
if (data.getName().equalsIgnoreCase(nm)) {
System.out.print(data.getName()+ " ada\n");
//std.re
data = (Student)std.getNext();
Student b = new Student("Umar","2004163943");
std.insertAtBack(b);
String name = "", matric = "", s = "";
boolean stop = false;
int size = std.size();
JOptionPane.showMessageDialog(null, size);
s = JOptionPane.showInputDialog("A: Add Student\nR: Remove Student" +
"\nV: View Sorted Student List\nS: Stop ");
while(!stop){
if (s.equalsIgnoreCase("A")){
name = JOptionPane.showInputDialog("Enter student name: ");
matric = JOptionPane.showInputDialog("Matric number: ");
Student student = new Student(name, matric);
std.insertAtBack(student);
s = JOptionPane.showInputDialog("A: Add Student\nR: Remove Student" +
"\nV: View Sorted Student List\nS: Stop ");
else if (s.equalsIgnoreCase("R")){
Student data = (Student)std.getFirst();
Student first = (Student)std.getFirst();
Student last = (Student)std.getLast();
JOptionPane.showMessageDialog(null, "First: "+ first+ "\nLast: "+ last);
String ns = JOptionPane.showInputDialog("Enter the student's name");
while (data != null) {
// buang kalau pd bhgn dpn
if (data.getName().equalsIgnoreCase(ns) && ns.equalsIgnoreCase(first.getName())) {
JOptionPane.showMessageDialog(null, first.getName());
JOptionPane.showMessageDialog(null, data.getName()+ " kena buang");
//std.removeFromFront();
std.remove(data);
s = JOptionPane.showInputDialog("A: Add Student\nR: Remove Student" +
"\nV: View Sorted Student List\nS: Stop ");
if (data.getName().equalsIgnoreCase(ns) && ns.equalsIgnoreCase(last.getName())) {
std.removeFromBack();
JOptionPane.showMessageDialog(null, data.getName()+ " kena buang");
s = JOptionPane.showInputDialog("A: Add Student\nR: Remove Student" +
"\nV: View Sorted Student List\nS: Stop ");
data = (Student)std.getNext();
}// habis while loop
// keluar jika pilih 's'
else if (s.equalsIgnoreCase("S")){ stop = true;}
else { JOptionPane.showMessageDialog(null, "Wrong input"); }
JOptionPane.showMessageDialog(null, std.print());
br.close();
pw.close();
}// end main class
}and here's the studentIn.txt data
Ahmad 2004199877
Hanif 2005378219
Zaki 2004456790
how can i do it? i mean to remove other than first element?
Message was edited by:
ikki_72> public class LinkedList extends java.util.LinkedList
// instance variables - replace the example below with your own
private ListNode firstNode;
private ListNode lastNode;
private ListNode currNode;
private String name;
[ ... ]Eeeeeeeeeew! Don't do that ever again! A java.util.LinkedList is very
well capable of managing a linked list (it is a linked list after all).
Either build your own linked list mechanics or use a LinkedList as
one of the member variables of your class, but please don't do this.
kind regards,
Jos ( ... that was scary ... ) -
Add,Get,Remove in linked lists
I need to be able to add, get and remove items from the linked list and I can't seem to be able to get any of it to work. Ignore the coments, that's just where I was experimenting with other ways of doing it. I keep getting an error from inside case1 of Menu. Any ideas appreciated.
import cs1.Keyboard;
import StaffMember;
import Employee;
import java.util.*;
public class Staff
LinkedList myList = new LinkedList();
public Staff ()
//StaffMember staffList = new StaffMember[1];
//private Employee[]firm;
//private int currentSize;
//private int count;
public static void main (String[] args)
Menu();
Employee[] staffList = new Employee[1];
for (int i=0; i<1; i++)
//staffList[i] = setNewEmployee();
//System.out.println (staffList); (NOT NEEDED)
//myList.add(staffList[i]);
//myList.size();
//myList.toArray();
for (int count=0; count<staffList.length; count++)
System.out.println (staffList[count]);
System.out.println ("- - - - - - - - - - - - - - - - -");
public static int Menu()
System.out.println("To add a new staff member press 1");
System.out.println("To find a staff member press 2");
System.out.println("To remove a staff member press 3");
int choice = Keyboard.readInt();
int effect = choice;
switch(effect)
case 1:
System.out.println("Adding new staff member");
setNewEmployee();
myList.add(new Employee);
myList.toArray();
break;
case 2:
System.out.println("Finding staff member");
break;
case 3:
System.out.println("Removing staff member");
break;
default:
System.out.println("invalid entry!");
return choice;
private static Employee setNewEmployee()
String name, address, phone;
int staffID;
System.out.print("Input ID: ");
staffID = Keyboard.readInt();
System.out.print("Input Name: ");
name = Keyboard.readString();
System.out.print("Input Address: ");
address = Keyboard.readString();
System.out.print("Input Phone: ");
phone = Keyboard.readString();
Employee s = new Employee(name, address, phone, staffID);
return s;This should get you going:
case 1:
System.out.println("Adding new staff member");
// setNewEmployee(); // this returns an object but there is nothing to store it in
myList.add(setNewEmployee); // use the returned object as a direct argument
// myList.toArray(); // this returns an array of objects but nothing to store the array in
break;As you continue by uncommenting the code in the other sections of your program, you will find similar type of erros.
V.V. -
Problem with Queue and linked list
Hi... i've got an assignment it start like this.
You are required to write a complete console program in java includin main() to demonstrate the following:
Data Structure: Queue, Priority Queue
Object Involved: Linked-List, PrintJob
Operations Involved:
1. insert
2. remove
3. reset
4. search
Dats all... I've been given this much information... Can any1 try to help me please... How to make a start??? And wat does the print job means???
Can any1 tell me wat am supposed to do...Hi,
Why don't you start your demo like this?
import java.io.IOException;
public class Demo {
public Demo() {
public void startDemo() throws IOException {
do {
System.out.println("String Console Demo ");
System.out.println("\t" + "1. Queue Demo");
System.out.println("\t" + "2. PriorityQueue Demo");
System.out.println("\t" + "3. LinkedList Demo");
System.out.println("\t" + "4. PrintJob Demo");
System.out.println("Please choose one option");
choice = (char) System.in.read();
showDemo(choice);
} while (choice < '1' || choice > '4');
public void showDemo(char ch) {
switch (ch) {
case '1':
System.out.println("You have chosen Queue Demo ");
showOperations();
break;
case '2':
System.out.println("You have chosen Priority Queue Demo ");
showOperations();
break;
case '3':
System.out.println("You have chosen LinkedList Demo ");
showOperations();
break;
case '4':
System.out.println("You have chosen Print Job Demo ");
showOperations();
break;
private void showOperations() {
System.out.println("Please choose any operations ");
System.out.println("\t" + "1. Insert ");
System.out.println("\t" + "2. Remove ");
System.out.println("\t" + "3. Reset ");
System.out.println("\t" + "4. search ");
public static void main(String[] args) throws IOException {
Demo demo = new Demo();
demo.startDemo();
private char choice;
Write a separate classes for the data structures show the initial elements and call the methods based on the operations then show the result.
Thanks -
Help needed in linked lists...
I have been working on this computer assignment lately but I still don't understand linked lists yet..I did an assignment on array based implementation and now I am supposed to do the same thing in linked list implementation..
I need help on how to change this into a linked list implementation..any help would be appreciated. Thank you..below is the code for the array based implementation..the only thing that needs change here is after where is says Array-based implementation of the ADT list.
public class ListArrayBasedDriver {
public static void main(String [] args) {
ListArrayBased myGroceryList = new ListArrayBased();
myGroceryList.add(1,"milk");
myGroceryList.add(2,"eggs");
myGroceryList.add(3,"butter");
myGroceryList.add(4,"pecans");
myGroceryList.add(5,"apples");
myGroceryList.add(6,"bread");
myGroceryList.add(7,"chicken");
myGroceryList.add(8,"rice");
myGroceryList.add(9,"red beans");
myGroceryList.add(10,"sausage");
myGroceryList.add(11,"flour");
printList(myGroceryList); //print out original List
System.out.print("numItems is now: " + myGroceryList.size() + "\n");
System.out.println("adding juice for 5th item...");
myGroceryList.add (5, (Object) "juice"); //add juice
System.out.println("item 5 is: " + myGroceryList.get(5)); //get position 5
printList(myGroceryList);
System.out.print("numItems is now: " + myGroceryList.size() + "\n");
System.out.println("removing juice...");
myGroceryList.remove (5); //remove item at position 5
printList(myGroceryList);
System.out.print("numItems is now: " + myGroceryList.size() + "\n");
public static void printList(ListArrayBased myList)
//method prints a list, numbering the values, e.g, "1. milk" .... "5. juice".... etc.
int i;
for(i=1; i <= myList.size(); i++)
String tempString = new String((String)myList.get(i));
System.out.println(i+" "+ tempString);
// Array-based implementation of the ADT list.
class ListArrayBased {
private static final int MAX_LIST = 50;
private Object items[]; // an array of list items
private int numItems; // number of items in list
public ListArrayBased()
// creates an empty list
items = new Object[MAX_LIST];
numItems = 0;
} // end default constructor
public boolean isEmpty()
return (numItems == 0);
} // end isEmpty
public int size()
return numItems;
} // end size
public void removeAll()
// Creates a new array; marks old array for
// garbage collection.
items = new Object[MAX_LIST];
numItems = 0;
} // end removeAll
public void add(int index, Object item) throws ListIndexOutOfBoundsException
if (numItems > MAX_LIST)
throw new ListException("ListException on add");
} // end if
if (index >= 1 && index <= numItems+1)
// make room for new element by shifting all items at
// positions >= index toward the end of the
// list (no shift if index == numItems+1)
for (int pos = numItems; pos >= index; pos--) {
items[translate(pos+1)] = items[translate(pos)];
} // end for
// insert new item
items[translate(index)] = item;
numItems++;
else
{ // index out of range
throw new ListIndexOutOfBoundsException(
"ListIndexOutOfBoundsException on add");
} // end if
} //end add
public Object get(int index) throws ListIndexOutOfBoundsException
if (index >= 1 && index <= numItems)
return items[translate(index)];
else
{ // index out of range
throw new ListIndexOutOfBoundsException(
"ListIndexOutOfBoundsException on get");
} // end if
} // end get
public void remove(int index) throws ListIndexOutOfBoundsException
if (index >= 1 && index <= numItems)
// delete item by shifting all items at
// positions > index toward the beginning of the list
// (no shift if index == size)
for (int pos = index+1; pos <= size(); pos++) {
items[translate(pos-1)] = items[translate(pos)];
} // end for
numItems--;
else
{ // index out of range
throw new ListIndexOutOfBoundsException("ListIndexOutOfBoundsException on remove");
} // end if
} // end remove
private int translate(int position) {
return position - 1;
} // end translate
} // end ListArrayBased
class ListException extends RuntimeException
public ListException(String s)
super(s);
} // end constructor
} // end ListException
class ListIndexOutOfBoundsException
extends IndexOutOfBoundsException {
public ListIndexOutOfBoundsException(String s) {
super(s);
} // end constructor
} // end ListIndexOutOfBoundsExceptionCould someone check for me if this will work and if it doesn't what I need to do to make it work..Thanks...
public class ListArrayBasedDriver {
public static void main(String [] args) {
ListArrayBased myGroceryList = new ListArrayBased();
myGroceryList.add(1,"milk");
myGroceryList.add(2,"eggs");
myGroceryList.add(3,"butter");
myGroceryList.add(4,"pecans");
myGroceryList.add(5,"apples");
myGroceryList.add(6,"bread");
myGroceryList.add(7,"chicken");
myGroceryList.add(8,"rice");
myGroceryList.add(9,"red beans");
myGroceryList.add(10,"sausage");
myGroceryList.add(11,"flour");
printList(myGroceryList); //print out original List
System.out.print("numItems is now: " + myGroceryList.size() + "\n");
System.out.println("adding juice for 5th item...");
myGroceryList.add (5, (Object) "juice"); //add juice
System.out.println("item 5 is: " + myGroceryList.get(5)); //get position 5
printList(myGroceryList);
System.out.print("numItems is now: " + myGroceryList.size() + "\n");
System.out.println("removing juice...");
myGroceryList.remove (5); //remove item at position 5
printList(myGroceryList);
System.out.print("numItems is now: " + myGroceryList.size() + "\n");
public static void printList(ListArrayBased myList)
//method prints a list, numbering the values, e.g, "1. milk" .... "5. juice".... etc.
int i;
for(i=1; i <= myList.size(); i++)
String tempString = new String((String)myList.get(i));
System.out.println(i+" "+ tempString);
// Linked List-based implementation of the ADT list.
class ListNode
//class to represent one node in a list
class ListNode
//package access members; List can access these directly
Object data;
ListNode nextNode;
//contructor creates a ListNode that refers to object
ListNode( Object object)
this( object, null );
} //end ListNode one-argument constructor
//constructor creates ListNode that refers to
// Object and to the next ListNode
ListNode ( Object object, ListNode node)
data = object;
nextNode = node;
// end ListNode two-argument contructor
//return reference to data in node
Object getObject()
return data; // return Object in this mode
//return reference to next node in list
ListNode getNext()
return nextNode; // get next node
} // end method getNext
} //end class ListNode
//class List Definition
public class List
private ListNode firstNode;
private ListNode lastNode;
private String name; // string like " list " used in printing
//contructor creates empty List with " list " as the name
public List()
this(" list ");
} //end List no-arguement constructor
//contructor creates an empty list with a name
public List( String listName )
name = listname;
firstNode = lastNode = null;
} //end List no-arguement contructor
//insert Object at front of List
public void insertAtFront ( object insertItem )
if ( isEmpty() ) //firstNode and lastNode refer to same object
firstNode = lastNode = newListNode( insertItem );
else // firstNode refers to new node
firstNode = new ListNode ( insertItem, firstNode );
} // end method insertAtFront
// insert Object at end of List
public void insert AtBack ( Object insertItem )
if ( isEmpty() ) //firstNode and lastNode refer to same object
firstNode = new ListNode ( insertItem );
else // firstNode refers to new node
firstNode = new ListNode (insertItem, firstNode );
} // end method insertAtFront
// insert Object at end of List
public void insertAtBack ( Object insertItem )
if ( isEmpty() ) //firstNode and LastNode refer to same Object
firstNode = lastNode = new ListNode ( insertItem );
else // lastNode = lastNode.nextNode = new ListNode ( insertItem );
} // end method insertAtBack
//remove first node from List
public Object removeFromFront() throws EmptyListException
if( isEmpty() ) //throw exception if list is empty
throw new EmptyListException( name );
object removedItem = firstNode.data; //retrieve data being removed
// update references firstNode and lastNode
if (firstNode == lastNode )
firstNode =lastNode = null;
else
firstNode = firstNode.nextNode;
return removedItem; // return removed node data
} //end method removeFromFront
//remove last node from List
Public Object removeFromBack() throws EmptyListException
If ( isEmpty() ) // throw exception if list is empty
throw new EmptyListException( name );
Object removedItem = lastNode.data; // retrieve data being removed
// update references firstNode and lastNode
If ( firstNode == lastNode )
firstNode = lastNode = null;
else // locate new last node
ListNode current = firstNode;
// loop while current node does not refer to lastNode
while ( current.nextNode != lastNode )
current = current.nextNode;
lastNode = current; // current is new lastNode
current.nextNode = null;
} // end else
return removedItem; // return removed node data
} // end method removeFromBack
// determine whether list is empty
public boolean isEmpty()
return firstNode == null; // return true if list is empty
} // end method isEmpty
//output List contents
public void print()
if (isEmpty() )
System.out.printf(�Empty %s\n�, name );
return;
System.out.printf(�The %s is: �, name );
ListNode current = firstNode;
//while (current != null )
System.out,printf(�%s �, current.data );
current = current.nextNode;
} //end while
System.out.println( �\n� );
} //end method print
} end class List -
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! -
Hello,
I am working with circular linked Lists. Now the thing is that my assignment was to make this. I had to write a set of methods. Now the thing is that I had to write a method that removes the last value. I made it but it doesnt wark and also i am confused
public Object removeFirst()
if(size()==0)
return "empty list";
Object temp = last.getNext().getValue();
last.setNext(last.getNext().getNext());
size--;
return temp;
//doesnt Work
public Object removeLast()
public Object removeLast()
if (size()==0)
return "empty list";
Object temp= null;
temp = last.getNext().getValue();
last = last.getNext();
size--;
return temp;
}Well what is wrong with the code?
Does it compile?
Does it throw an error at runtime?
Does it give you an unexpected answer?
For solving problems like this with next/prev "pointers" I find diagramming boxes with arrows to help understand is an absolute requirement. Try figuring it out on paper.
If you are removing the last item in the list, that means that the item directly before this one, has to the next one in the list
Assuming you have a structure like this:
...--> (n-1) --> (n) --> (1) --> (2) -->...(n-1)Then removing item (n) you have to make (n-1) point at item (1) as item (n-1) becomes the new "last"
So you have to have the item before the "last" element to keep the next/prev pointers correct. -
Hi,
I'm developing a circular linked list class.. However everytime I add to the front of the list it overwrites the first element in the list.. I pretty confused at the moment. If anyone could assist me in what I'm doing wrong it would be greatly appreciated..
My Class:
public class CNode<T>
public T nodeValue; //data held by the node
public CNode<T> next; //next node in the list
//default constructor; next references node itself
public CNode()
nodeValue = null;
next = this;
//constructor; initializes nodeValue to item
//and sets the next to reference the node itself
public CNode(T item)
nodeValue = item;
next = this;
}My addFirst:
public static <T> void addFirst(CNode<T> header, T item)
CNode<T> curr;
CNode<T> newNode = new CNode<T>(item);
//header.next = newNode;
//newNode.next = header;
curr = header;
newNode.next = header;
curr.next = newNode;
}You need a Node class and a class that manages the nodes. The class the manages the nodes is typically called something like MyLinkedList. The MyLinkedList class will typically have a member called 'head' or 'first' and another member called 'last', 'end', or 'tail'. Those members will contain references to the first node and the last node respectively.
The methods like add(), remove(), find(), etc. will be members of the MyLinkedList class--not the Node class. The add() method of the MyLinkedList class will create a node, set the value of the node, and then set the next member to refer to the proper node or null if the node is added to the end of the list. Therefore, there is really no need for a default constructor in the node class. The MyLinkedList class will always set the value of the node, and then set it's next member to refer to something.
You might want to try to write a linear linked list first, and get that working, and then modify it to make it a circular linked list. In addition, you should be drawing pictures of nodes with arrows connecting the different nodes to understand what's going on. Whenver the next member of a node refers to another node, draw an arrow starting at the next member and ending at the node it refers to. The pictures will be especially helpful when you write functions like add().
Message was edited by:
7stud -
Comparable linked list sorting
i have been trying to find a way to sort a link listed. After some reading i found out that it is probably best to use collections.sort(list). I think i understand how to implement it , i need to declare a compareto and equals method. However, most of the reading i have done shows how to create a collection from a linked list and add items to the collection and sort them, however it doesn show how to copy this sorted collection back inot a linked list. I need to remove items and add items to the sorted linked list. Is it possible to create a linked list, sort it using the collection sort and return the sorted linked list? I have looked in the api's but got confused!!
You don't need to copy anything.
List list = new LinkedList(); // or ArrayList
// list.add stuff
Collections.sort(list); Assuming whatever you added to the list implements Comarable, the list is now sorted. -
I have a doubly linked list and I wrote two methods, one to insert items at a specified index and one method to remove items at a specified index. I am not 100% sure if I wrote these methods correctly. Well I'm pretty sure I messed something up because I'm having trouble implementing a swap method and I think this is where the problem lies.
* @param o the object to insert.
* @param i the index to add the object.
public void insertAt(Object o, int i) {
if (i==0) {
prepend(o);
else {
int j= 0;
Node previous= first;
Node next= first;
while (j<i) {
previous= next;
next= previous.getNext();
j++;
Node insertAt= new Node(o, previous, next);
previous.setNext(insertAt);
insertAt.setPrevious(previous);
insertAt.setNext(next);
next.setPrevious(insertAt);
size++;
* @param i the index of the object to remove.
public Object removeAt(int i) {
if (i==0) {
removeFirst();
return first.getData();
else {
int j= 0;
Node previous= first;
Node next= first;
while (j<i) {
previous= next;
next= previous.getNext();
j++;
Node temp=next.getNext();
if (temp.equals(null)) {
previous.setNext(null);
last= previous;
return next.getData();
previous.setNext(temp);
temp.setPrevious(previous);
return next.getData();
}public Object removeAt(int i) {
if (i==0) {
removeFirst();
return first.getData();
}I can't be sure from the code but the above code looks like a problem: if you remove the node before you get the data, aren't you returning the data from the second node (now the first)? -
Hi,
I have an assignment on linked lists, as a beginner I am really struggling with it for hours...
I have to write the following methods without importing any libraries.
"Write an iterative method delete() for LinkedStackOfStrings that takes an integer parameter k and deletes the kth element (assuming it exists).
Write a method find() that takes an instance of LinkedStackOfStrings and a string key as arguments and returns true if some node in the list has key as its item field, false otherwise."
It must be implemented in the code on this site:
[http://www.cs.princeton.edu/introcs/43stack/LinkedStackOfStrings.java.html]
Help would be appreciated! I have been trying for hours :(vdL wrote:
Thanks for the reply! Yes, I forgot add what my actual problem is.
If I am correct, I will need to be able to traverse through the list up to a certain point, redirect and redirect the pointers.
My problem is I am able to traverse through the list using 'for(Node x = first; x != null; x= x.next)' but I do not know how make it only run up to a particular position in the list.You can keep an integer counter, increment it each time through the loop, and break out of the loop when the counter is big enough. Example of breaking:
if (n == k) break;
And also, how not to loose the previous Node when traversing trough the list.You're allowed to have multiple references. So you could keep one reference to the current node, and one reference to the one before it.
Or, rather than looping through the list until you find the kth element, loop until you find the (k - 1)th element, then (if it exists) remove the one after it.
Maybe you are looking for
-
External drive crash, disk utility unable to repair
I have a 250GB LaCie external disk. I use it to store files that I use with Final Cut. Unfortunately I had a Final Cut crash while the disk was running (or maybe it was the external disk that crashed). This has caused my disk to cease operation. Mac
-
Hi by mistake i deleted my viber messages how to get them back
Hello i deleted my messages by mistake ...is there any way that i get my messages back thankyou
-
Link to javadoc doc folder in your webpage
Hi all, I'm new to iWeb. I have a folder named "doc" filled with html pages that has been produced as an API for my project through Eclipse. My question , I created a new site and I want to add a hyperlink to this folder to show the project API. Th
-
How do I identify and install latest RAW plug in for elements 10 for Sony A 7 mark 2
How do I identify and install latest RAW plug in for elements 10 for Sony A 7 mark 2
-
HT201400 Error during creat an Apple ID
Hi When I want to creat an Apple ID I take this error : (For assistance, contact iTunes Support at www.apple.com/support/itunes/ww/.) and i don't know what should I do to solve this problem please help me Thanks