Inserting into a linked list
Hello all,
I'm currently studying for a midterm on linked lists and I'm having a little trouble inserting in "order". What I'm trying to do is use a compareTo method to compare serial numbers of items. The compareTo methos is as follows:
public int compareTo(Object obj) {
StoreItem other = (StoreItem) obj;
return serialNumber - other.serialNumber;
And the following is my addItem method....which should simply insert the Node into the list in it's proper place according to it's serial number. Any help would be greatly appreciated:)
public boolean addItem(StoreItem item){
if (item == null)
return false;
else if (first == null)
{first = new Node (item, null);
return true;}
else {
Node p = first;
while (p.next != null && item.compareTo(p.value) > 0){
p = p.next;
p.next = new Node (item, p.next);
return true;
Thanks again!
Tyler
My error lies in the "else {" section of the code....The code up to there works fine as I've tried adding one element to an empty list and print it and it works. What doesn't work is when there's already one item in my list and I want to add another, which is what the following code was meant to do:
else {
Node p = first;
while (p.next != null && item.compareTo(p.value) > 0){
p = p.next;
p.next = new Node (item, p.next);
return true;
This code compiles and doesn't give me a runtime error, yet when I execute the program, it only seems to add the first element....
Thanks again for the help:)
Tyler
Similar Messages
-
Read Hashmap into a Linked List
Hi,
I have a hashmap containing objects; I want to put those objects into a linked list.
Where do I start? I haven't the foggiest idea....
I suppose I have to iterate through the hashmap and extract the objects and then put them into a linked list.
Does anyone know of a good tutorial for that kind of thing?
Cheers,
DidheI'm no expert on this (far from it), but on looking
at the HashMap and LinkedList API's, there may be
something easy available to you.Yes, another URL to bookmark:
http://java.sun.com/javase/6/docs/api/ -
Unwanted file extension inserted into file format list!
I accidentally saved a .wav file with the .ses extension. Now I've got the .ses extension included with .wav and .bwf extensions under the Save As Type box in my Save and Save As dialog windows. Any advice on removing it?
I just recreated your issue. I saved a .wav file with the .ses extension at the end. It did indeed put the .ses extension in with the .wav and .bwf extensions next to Windows PCM Wave File.
I got rid of this by opening the affected file, doing a Save As, deleting the .ses extension from the file name when naming the file, then saving. I closed the file, closed Audition, reopened Audition and the .ses extension was gone from the Windows PCM Wave File list. -
I am writing a program for an assignment that reads a file containing population growth for all the Counties in the U.S. I'm required to use a link list to store the data. They want me to sort the data based on certain criteria. My first problem is that as each new County instance is created, it is to be inserted into this linked list in alphabetical order first by county name.
My understanding of linked lists is that they cannot be randomly accessed like a vector or an array. So is it possible to do this without using a vector or an array? And how would I go about it?
thanks.Can you create a second, sorted linked list?The prof. didn't specify whether or not I can use a second list.
Are you prohibited from using the collections framework (probably, if it is a school assignment!)Not really sure on this one. Again it is not specified in the assignment
(Why would they have you store this data in a linked list??)I their reasoning is to have us learn how to implement linked list because it can grow or shrink when necessary.(Other than that I don't understand the practicality of it either)
Are you using a doubly linked list (forwards and backwards)?The assignment does not specify a certain linked list to use.
Did your prof mention any sort algorithms you might use? He states later in the assignment that I have to generate different growth reports by using MergeSort.
I appreciate your help and comments. Unfortunately my prof. is very vague about the assignment and its implementation in his outline. He just kind of throws us into it hoping that we will figure it out. -
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 -
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(); -
C/C++ Alphabetical Linked List
For my programming class, we have to create a linked list, which is arranged in order of when you added them. This was Assignment Six. Assignment 8 is to add an alphabetical list to this program, alongside the list in order.
My professor wants us to have a "donor struct" and an "alpha struct" that points to the donor, as well as the next in the list.
He isn't helping me figure this out so I figured I'd ask for help here.
My 'modifyDonor()' function is broken, it deletes everything after whatever record you are trying to modify. There is also a problem in my 'prepareFiles()' function. Whatever the last entry is, is copied in twice.
I would rather have this alphabetical stuff figured out before I work on those things.
I'm not really allowed to use C++ stuff (classes, objects, etc.), because we haven't learned them yet, but if you can do it, and figure it out, then explain it to me. I'll take it.
(Also, if you could post the edits to my source code, that would rad!)
Below is a link to my source code and data file.
http://www.dcpwrpodcast.com/DCPWR/Help.Sponsorhipfiles/Archive.zip
Any help you can provide is greatly appreciated!Unfortunately, I can't really pinpoint an exact place where you are doing something wrong. I don't think you really understand the linked list concepts yet. The first thing I changed was getting rid of where you increment "first" in modifyDonation. Resetting "first" effectively destroys your list. You have additional problems with the other pointers.
So, first of all, you have too many global pointers. You need one global pointer, named "head". Any time you iterate through the list (to print, find, etc.) you create a temp donor pointer, assign "head" to it and increment that temp pointer. The last node in your list should have NULL as its "next" pointer.
To add a node, create a new node with NULL as its next pointer. Find where you want to insert, make the new node's next pointer point to the next pointer of the node at the insertion point. Then make the next pointer of the node at the insertion point point to the new node.
To delete a node, find the node to delete. Make the previous node's next pointer point to the dead node's next pointer. Then delete the node.
You don't change any pointers (other than temp ones) during a modify or print.
At this point, all you have left is the special case of the first node. The last node isn't special because you can do the same copying of the next pointer as normal, even though that pointer is NULL.
The first node, however, needs careful handling. If you delete the first node, you have to reset your head pointer. If you insert a new first node, you have to reset your head pointer. Sometimes it is easier to have your head node be a special, empty node. Then, you don't have to re-assign head. Also, when searching through the list, your "current" pointer should be the "previous" node. That way, when you are ready to insert, your "current" pointer is the "previous" node and the insertion is easy. The code looks a bit ugly because you'll have things like "if(current->next && current->next->id == id)". But you'll also need an extra, redundant null check.
Hopefully this makes some sense. Your code is more complicated than it needs to be. You have too many globals. You are modifying those globals far too frequently. You want lots of:
void modifyDonation(donor * node);
donor * current = head->next;
while(current)
if(current->id == id)
modifyDonation(current);
break;
current = current->next;
insert and delete are more difficult
void insertDonation(donor * previous, donor * next);
donor * current = head;
while(current)
if(!current->next || (current->next->id == id))
insertDonation(current, current->next);
break;
current = current->next;
To maintain a natural order and a sorted order, you'll need two head pointers. After you add or insert into the natural list, you insert into the sorted list according to the sort criteria. Delete is the same for both lists. -
//I need to add a header node into this Linked list class and
// i dont understand it. can anyone give me a few pointers.
// This is the orginal code. What im trying to figure out is below.
public abstract class LinkedList implements ListInterface
protected class ListNode
// Used to hold references tolist nodes for the linked list implementation
protected Listable info; // the info in a list node
protected ListNode next; // a link to the next node on the list
protected ListNode list; // reference to the first node on the list
protected int numItems; // Number of elements in the list
protected ListNode currentPos; // Current position for iteration
public LinkedList()
// Creates an empty list object.
numItems = 0;
list = null;
currentPos = null;
public boolean isFull()
// Determines whether this list is full.
return false;
public int lengthIs()
// Determines the number of elements on this list.
return numItems;
public abstract boolean isThere (Listable item);
// Determines if element matching item is on this list.
public Listable retrieve (Listable item)
// Returns a copy of the list element with the same key as item.
ListNode location = list;
boolean found = false;
while (!found)
if (item.compareTo(location.info) == 0) // if they match
found = true;
else
location = location.next;
return location.info.copy();
public abstract void insert (Listable item);
// Adds a copy of item to this list.
public void delete (Listable item)
// Deletes the element of this list whose key matches item�s key.
ListNode location = list;
// Locate node to be deleted.
if (item.compareTo(location.info) == 0)
list = list.next; // Delete first node.
else
while (item.compareTo(location.next.info) != 0)
location = location.next;
// Delete node at location.next.
location.next = location.next.next;
numItems--;
public void reset()
// Initializes current position for an iteration through this list.
currentPos = list;
public Listable getNextItem ()
// Returns copy of the next element in list.
Listable nextItemInfo = currentPos.info.copy();
if (currentPos.next == null)
currentPos = list;
else
currentPos = currentPos.next;
return nextItemInfo;
//now heres the part i dont get i need to make list point to a new
// node say HeaderNode. Now wouldnt just...
public LinkedList()
// Creates an empty list object.
numItems = 0;
list.next = HeaderNode; //....this line do the trick???
currentPos = null;
I know that i cant use any insert methods to put it in, so what else could i possibly do?bump
-
I was wondering how i could get my code to insert the tokenized string into a linked list. I would need each word to be a different element so that I could perform a bubble search upon them. Can anyone help me please? Below is my code:
import java.io.*;
import java.util.*;
public class ScanText {
public static void main(String[] arguments) {
try {
File output = new File("printout.txt");
FileReader scan = new
FileReader("sample.txt");
BufferedReader in = new
BufferedReader(scan);
FileWriter fw = new
FileWriter(output);
BufferedWriter bw = new
BufferedWriter(fw);
while (in.ready()) {
String str = in.readLine();
StringTokenizer tk = new StringTokenizer(str);
while (tk.hasMoreTokens()) {
System.out.println(tk.nextToken());
}catch (IOException e) {
System.out.println("Error -- " + e.toString());I've established a LinkedList but I still can't figure out how to add each token then sort them into alphabetical order...I'm new to java, but I posted this on the wrong forum...I've never done a bubble sort before either. Would i have to do it using a for loop or an if function?
-
Hello,
I am a college student and I am writing a program for a Data Structures course I am currently taking. The assignment is to write a program that calculates the number of electoral votes each state receives. The program is to read in the name and population of each state from a text file, place it into a linked list, and calculate the number of electoral votes each state gets.
I have started the assignment, but I am unsure of how to proceed on reading the data in from the text file and placing it into a linked list. Also, I am unsure of how to parse the linked list to get the integer value of the population to be used for the calculation.
Anyone out there have any ideas or advice to offer? Any information will be greatly appreciated.
Thanks!You're basically asking about the entire assignment. I live by the credo "Fish for a man and he'll eat for a day, but teach him how to fish and he'll eat for a lifetime." so let's teach you how to fish.
You're lucky Java has an API on the web where you can look up all these wonderful classes that have already been written for you:
http://java.sun.com/j2se/1.4.1/docs/api/
So like I posted before, RTFM.
"But there are soooo many classes! Where do I start?"
Well, lets look at your posting a LinkedList eh? Just so happens java has one of those click on it, look at ALL the methods and fields, see if that works for you.
Repeat this for all the various classes you'll need. This is how programmers get stuff done. A lot of the time when you start out doing something you don't know how to do it, so you research until you find the answer, cause in the real world it isn't always the case that you can ask your TA for help. (But, then again, that's what these forums are for.)
So, just so I leave you with something tangible that will get you started, let me suggest looking at the following Java classes:
java.io.FileReader
java.io.StringTokenizer
java.util.LinkedList
java.lang.Integer
You could use all or none of these to do what you want, but using them (properly) will probably get you through your assignment the fastest. And definitely through future assignments faster.
theSparko strikes again! -
Elements overwrites each others in Linked List
hello, my problem is mentioned as the subject.
i'm trying to add the same object into a linked list each time with different values, however it doesn't work and eventually all objects stored in the linked list become identical.
here's the sample code.
public class Object1
private String s = null;
public Object1(){}
public void setS(String s){this.s = s;}
public String getS(){return s;}
import java.io.*;
import java.util.List;
import java.util.LinkedList;
import java.util.Collections;
public class Test
public static void main(String[] args)
List ll = Collections.synchronizedList(new LinkedList());
Object1 obj1 = new Object1();
obj1.setS("111111");
ll.add(obj1);
for (int i=0; i<ll.size(); i++)
Object1 obj2 = (Object1)ll.get(i);
System.out.println(">>>>>before:: " + obj2.getS() + "\n");
obj1.setS("2222222");
ll.add(obj1);
for (int i=0; i<ll.size(); i++)
Object1 obj2 = (Object1)ll.get(i);
System.out.println(">>>>>after:: " + obj2.getS());
and the result looks like this:
before:: 111111
after:: 2222222
after:: 2222222what i really want is something like this instead:
before:: 111111
after:: 111111
after:: 2222222could any one please help
thanks in advance
cedriccYou need to understand the distinction between references and objects. You're not storing objects in the linked list, but references. All of these references point to the same object. You need to create a new object each time through the loop.
-
Help with linked list code.
Here's a basic linked list code that I need help on.
What I need assistance with:
1. How would I rewrite and delete words/phrases in the file IO section of my code?
2. How would I make the code recognize all the words on each line of the linked list? Only the words on the first line of the file go into the linked list.
import java.util.LinkedList;
import java.io.*;
import javax.swing.JOptionPane;
public class LinkedLists {
public static void delete (LinkedList test)
int a = Integer.parseInt(JOptionPane.showInputDialog(null,
"Enter a position to delete"));
test.remove(a - 1);
System.out.print(test);
public static void add (LinkedList test)
String user = JOptionPane.showInputDialog(null, "What to input?");
int b = Integer.parseInt(JOptionPane.showInputDialog(null,
"What position to enter it in?"));
test.add(b - 1, user);
System.out.print(test);
public static void fileRead(LinkedList test) throws IOException
BufferedReader fileIn;
String text;
fileIn = new BufferedReader(new FileReader("z:/data.txt"));
text = fileIn.readLine();
fileIn.close();
int b = Integer.parseInt(JOptionPane.showInputDialog(null,
"What position to enter it in?"));
test.add(b - 1, text);
System.out.print(test);
public static void fileWrite(LinkedList test) throws IOException
PrintWriter fileOut;
fileOut = new PrintWriter(new FileWriter("z:/data.txt",true));
String user = JOptionPane.showInputDialog(null, "What to input?");
fileOut.println(user);
fileOut.close();
fileRead(test);
public static void main(String[] args) {
LinkedList test = new LinkedList();
test.addLast("Fly");
test.addLast("money");
test.addLast("awesome");
test.addLast("woot");
test.addLast("yay");
System.out.print(test);
System.out.println();
int x = Integer.parseInt(JOptionPane.showInputDialog(null,
"Enter \n1 to Delete \n2 to Add \n3 to read data from file \n4 to write into the file and add to list"));
if (x == 1) {
delete(test);
if (x == 2) {
add(test);
if (x == 3) {
try {
fileRead(test);
} catch (IOException e) {
e.printStackTrace();
if(x==4)
try {
fileWrite(test);
} catch (IOException e) {
e.printStackTrace();
}Edited by: Johnston on Sep 16, 2007 1:13 AMHi,
Johnston wrote:
1. How would I rewrite and delete words/phrases in the file IO section of my code?You want to replace or remove in/from the file?
First you have to define a file format. This is not a Java technical term, but a thing what you have to keep in mind. Simplest format is:
- each ListItem is one line in the file closed with newline.
Now you can read the file line by line and store the lines in a memory structure (LinkedList for ex ;-)). Then replace or remove the designated elements an write the file new by iterate over the list and write each item as line in the file.
Johnston wrote:
2. How would I make the code recognize all the words on each line of the linked list? Only the words on the first line of the file go into the linked list.You have to read the file line by line and then add each line as item of the list.
Examples for reading/writing textfiles:
http://www.exampledepot.com/egs/java.io/pkg.html#Reading%20and%20Writing
Btw: Deal with Generics (see http://java.sun.com/docs/books/tutorial/extra/generics/index.html) an use this knowledge to declate your List better.
greetings
Axel -
Inserting integers in a Linked list/List in Java
Please solve the following problem using Java.
Problem: Write a program that inserts 25 random integers from 0 to 100 in order in a linked list object. The program should calculate the sum of the elements and the floating-point average of the elements.
Thanks
Ripondo the following 25 times
. insert random value between x and y into my list
All you have to do is replace x and y with your values and compile using the java -idiot option. -
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! -
How to insert an HTML link into a page
Hello,
We have a list of documents in a external document management system. We would like to present the list of documents to the user for retrieval from within any SRM HTML page.
I was thinking of two different approaches:
1) I would like to be able to insert an HTML link to a URL of documents for display to the end user.
2) Alternatively, we might want to inject some javascript into the screen to handle the presentation of the links.
We would like this functionality to work on any of the screens within SRM as global functionality.
Any suggestions on how to customize SRM to handle this functionality request?
(Will reward points very quickly)
Thanks
Edited by: Aaron Jack on Feb 15, 2008 7:02 PM
Edited by: Aaron Jack on Feb 15, 2008 7:03 PMHi,
My project has a requirement to show URL in Bid Invitation screen. In turn, when user clicks that hyperlink, it will pop-up a web dynpro screen.
Maybe this is the same with your need.
In case this is the same, the trick is to define an additional field in bid invitation custom header with customized data element and customized domain.
Then, defined conversion exit for the domain with javascript line such as "<html> bla bla </html>" to pop-up the web dynpro screen in modal dialog.
The result will be as what I have above.
Hopefully this can help you.
Maybe you are looking for
-
HT3819 How can I share my music with another apple ID device
Can I share the music on my iPad with another iPad, the other iPad has a different Apple ID
-
I'm sure I'm not the only person with this problem. I am running Mavericks on a 21" iMac Early 2008. I have applied all updates. When I try to change preferences on almost all of the preference panes it can't be done. I click on the button and no
-
I have a Exchange 2013, That has been running for a few months now since we moved it over, but now I get the Microsoft Outlook Message "The Microsoft Exchange Administrator has made a change that requires you to quit and restart Outlook." It only sho
-
How do I get an iPhoto slideshow onto DVD?
I've done photo slideshows before, but tried this one in iPhoto and now can't get to a DVD. Should I use iDVD or iMovie? Thanks!
-
Hi, so I'm working on a form and I have 4 fields that require percentages inputted into them. I have a total box at the bottom of that which adds all this up, but I need this to stop calculating at 100%, in other words cap it at 100%. Is there a solu