Help with Stacked linked lists with nodes.
I have 5 elements, { object1, object2, object3, object4, object5}; and I add then to the stack from object1 to object5 (from left to right). So the head node > object 5 > object 4 > object3> object2 > object1. (> represents points to.) So i made a method to get the nth element of the list in the order I input it to the list. The method is called ElementsAt(int i). But some reason, it always returns the last object in the list. I included my entire code because there may be something wrong somewhere else that maybe causing it.
Note: There is also a list interface.
public class MyList implements List {
* The head node.
private Node head;
* The node it is currently reading
private Node curr;
* The previous node it has read.
private Node prev;
* A blank Node
private Node blank;
* The number of elements in the list
private int numItems;
* Default constructor
public MyList() {
numItems = 0;
head = null;
* Add an element in front of the list.
* @param o The object to be added.
public void addFront(Object o){
if(head == null) {
head = new Node (o, null);
else{
blank = new Node(o,null);
curr = head;
while (curr != null){
prev = curr;
curr = curr.getNext();
blank.setNext(curr);
prev.setNext(blank);
numItems +=1;
* Add an element in the back of the list.
* @param o The object to be added.
public void addBack(Object o){
curr = head;
if (head == null){
head = new Node(o ,null);
else {
head = new Node(o, curr);
numItems +=1;
* Determine whether the list contains a certain object.
* @param o The object it searches through the list to
* see if it is present.
* @ returns a boolean that describes whether object is
* in the list.
public boolean contains(Object o){
boolean present = false;
curr = head;
while ((curr != null) && (present != true)){
present = (o.equals(curr.getElement()));
curr.setNext(curr.getNext());
return present;
/** Remove an object in the list if it is in the list.
* @param o The object it wants to remove.
public void remove(Object o){
if(head ==null){
return ;
if(head.getElement().equals(o)){
head = head.getNext();
numItems -=1;
else{
prev = head;
curr = head.getNext();
while ((curr!=null) && (curr.getElement() !=o)){
prev = curr;
curr = curr.getNext();
if (curr!=null){
blank = curr.getNext();
prev.setNext(blank);
numItems-=1;
/** Determine what object is at the nth place of the list.
* @param i the nth place of the list
* if the number is higher than the list, it is invalid.
* @returns The element of the nth position of the list.
public Object elementAt(int i){
curr = head;
Object blank = "";
if ( i > numItems){
return null;
else{
i = numItems - i;
for (int j=1; j<=i; j++){
if(curr!=null){
blank = curr.getElement();
curr = curr.getNext();
return blank;
/** Determine the size of the list.
* @returns The size of the list
public int size() {
return numItems ;
/** Makes the list empty
public void makeEmpty() {
head = new Node(null,null);
numItems = 0;
/** Returns The list as a string.
* @returns String containing all elemnts of the list.
public String toString(){
String sum = "";
curr = head.getNext();
blank = head;
prev = head;
if(curr==null){
prev.setNext(null);
curr=prev;
while(curr != null)
if(curr.getNext() ==null){
sum += "\n" + curr.getElement();
curr.setNext(null);
if(curr.getNext()==null)
prev.setNext(null);
prev = blank;
curr = prev.getNext();
else{
curr = curr.getNext();
prev= prev.getNext();
if (head.getElement() !=null)
sum +="\n" + head.getElement();
return sum;
}this is the program i use to test it.
public class MyListTester {
public static void main (String [] args)
List list = new MyList();
String one = "Object One";
String two = "Object Two";
String three = "Object Three";
int five = 5;
list.addFront(one);
list.addFront(two);
list.addFront(three);
list.addFront(five);
System.out.println(list);
System.out.println();
System.out.println(list.size());
System.out.println(list.elementAt(2));
//this should print out object Two, but doesn't
System.out.println(list.elementAt(3));
//this should print out object Three, but doesn't
}
chuang7 wrote:
So i made a method to get the nth element of the list in the order I input it to the list.
* The node it is currently reading
private Node curr;
* The previous node it has read.
These ('curr' and 'prev') should be local variables in the methods that need them, not instance variables.
public void addFront(Object o)
while (curr != null){
prev = curr;
curr = curr.getNext();
blank.setNext(curr);At this point 'curr' is always null so this line is redundant.
public void addBack(Object o)You can reduce this method to two lines of code.
public boolean contains(Object o)
curr.setNext(curr.getNext());You are modifying the list inside the contains method?
for (int j=1; j<=i; j++){Rethink this loop.
public String toString()
prev.setNext(null);
if(curr.getNext() ==null)
sum += "\n" + curr.getElement()+"->"+curr.getNext();
curr.setNext(null);
if(curr.getNext()==null)
prev.setNext(null);
prev = blank;
curr = prev.getNext();You are modifying the list in the toString() method?
Similar Messages
-
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. -
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 -
Including Help in the Linked List Entries
Hi,
Can any one explain how to include Help text to the Linked List Entries like including normal help in the other APEX 2.2 items?
Thanks
ChitraHi santhosh
while you are creating the fieldcatalog there is a field called 'ROLLNAME' - Data element for F1 help.
If your F1 help is in reference to this data element you can specifiy it here so that it appears on the List viewer. Otherwise you have to create your own data element with the documentation and specify it here for it to appear.
In the Grid control, you can use events for triggering the same.
Hope this helps.
Reward points.
Regards
Meera -
Help abstract classes linked list
I have a base abstract class Vegetable which is basically Node for a linkedlist
The base class Vegetable has a few abstract methods Pumpkin, Carrot, Potato basically extends Vegetable
Another class called VegetableCollection
basically in VegetableCollection
can this be done if the objects are different types eg Pumpkin, potato, Carrot?
public void add(Vegetable addObject)
head = new Vegetable(addObject);
}I have a base abstract class Vegetable which is basically Node for a linkedlist
The base class Vegetable has a few abstract methods Pumpkin, Carrot, PotatoYou probably wouldn't have abstract methods with those names. Abstract methods are methods that you will need to define in every subclass. And a subclass called Pumpkin probably won't have meaningful definitions for methods called Carrot and Potato.
can this be done if the objects are different types eg Pumpkin, potato, Carrot?
public void add(Vegetable addObject)
head = new Vegetable(addObject);
}Here is an example of "polymorphism" at work:
import java.util.*;
abstract class Vegetable
public abstract void identify();
class Carrot extends Vegetable
public void identify()
System.out.println("I'm a Carrot.");
class Pumpkin extends Vegetable
public void identify()
System.out.println("I'm a Pumpkin.");
public class Test
public static void main(String args[])
LinkedList<Vegetable> myVegetables = new LinkedList<Vegetable>();
myVegetables.add(new Carrot());
myVegetables.add(new Pumpkin());
Iterator<Vegetable> i = myVegetables.iterator();
Vegetable v = null;
while(i.hasNext())
v = i.next();
v.identify();
output:
I'm a Carrot.
I'm a Pumpkin.To get polymorphism to work, you need to:
1) Define a base class with a method that you want in all the subclasses.
2) Override the method in the subclasses so that it does what's necessary for that subclass.
3) Store the subclass objects in a variable(or collection) whose type is the base class.
4) Call the method on the base type variable. Then through the magic of polymorphism, java will examine the actual object stored in the base type variable to determine what subclass it is, and then java will call the version of the method in that subclass.
As the previous poster mentioned, you need to define a class called Node, which has head, previous, and next members. Your Node class will also have a member variable called veggie, which will be of type Vegetable. Then you can assign a Carrot, Pumpkin, or Potato object to that member variable.
I assume this is an exercise where you have to create your own linked list. Otherwise, you can use the linked lists provided by java, which are very easy to use. -
Hello,
I have a double linked list where I want to change one node to another and change its references at the same time.
The nodes are not together i.e. they do not appear in the list consectutively.
I need to swap like B and D - I have managed to do swaps like A and B, and C and D (that took a while).
Is this logic correct (I am using temporary nodes):
if(f1 != (f2 - 1))
Object temp = object1;
Object temp2 = object2;
object1.getPrevious().setNext(object2);
object2.getNext().setPrevious(object1);
object1.getNext().setPrevious(object2);
object2.getPrevious().setNext(object1);
object1.setPrevious(temp2.getPrevious());
object1.setNext(temp2.getNext());
object2.setPrevious(temp.getPrevious());
object2.setNext(temp.getNext());
If this logic is not correct then please only give hints as to why.
CheersHello,
I have a double linked list where I want to change
one node to another and change its references at the
same time.
The nodes are not together i.e. they do not appear in
the list consectutively.
I need to swap like B and D - I have managed to do
swaps like A and B, and C and D (that took a while).
Is this logic correct (I am using temporary nodes):
if(f1 != (f2 - 1))
Object temp = object1;
Object temp2 = object2;
object1.getPrevious().setNext(object2);
object2.getNext().setPrevious(object1);
object1.getNext().setPrevious(object2);
object2.getPrevious().setNext(object1);
object1.setPrevious(temp2.getPrevious());
object1.setNext(temp2.getNext());
object2.setPrevious(temp.getPrevious());
object2.setNext(temp.getNext());
If this logic is not correct then please only give
hints as to why.
CheersI didn't check your logic, but I think that there are errors in it since I saw these lines:
object1.setPrevious(temp2.getPrevious());
object1.setNext(temp2.getNext());
object2.setPrevious(temp.getPrevious());
object2.setNext(temp.getNext()); temp and temp2 are not copies of object1 and object2. They are references to the same object, so when you do e.g. object1.getPrevious().setNext() you also change previous->next for temp.
temp == object1
temp2 == object2
Kaj -
Cannot open node toad from the dock,can view the icom but won't open!!
Unfortunately it's not available in my country for downloading so I can't troubleshoot it.
Have you confirmed that you are running the latest version? It looks like they recently updated it on June 30th.
http://itunes.apple.com/au/app/nodetoad/id534412560 -
Need help in solving Linked lists queries
I have encountered this code
part a
Node head, tail;
head = null;
tail = null;
head = new Node("Beef", head); //what does that mean?part b
Node head, tail;
head = null;
tail = null;
node new 3 = new Node("Pork");
tail.next = new3;
tail = new3;I am told to use diagrams to show the results of these codes. How to go about solving it?part aWhat do you think? You can see that it creates a node, and it assigns the new node to head.
part bSame applies here. What do you think it does? You can see that it creates a new node, and uses the tail variable.
Try draw it all on a paper. -
Please help me :'( , I really need help in Linked List & Recursion program.
Hi everybody..
I hope all of you are ok..
I'm new member in this forum and I hope anyone can help me in Linked List $ Recursion issue..
I should write a Java program that implements a linked list of objects. This program / class will have the following methods:
1- //print each node starting from startNode upto the end node in the list
void writeList(Node startNode)
2- //insert a new element to the end of the list
void insertEnd(Object element)
3- //Print each element statring from first element in list to the last element then start //printing each element from the last element to the first element
void writeMirror()
4- //delete the last node.
void deleteEnd()
5- //returns the number of the nodes in the list.
int lengthList(ListNode x)
Implement the above methods using the following restrictions:
1- All above methods must be implemented as a recursive method.
2- For the given linked list class, there is only a head reference
variable, pointing the beginning of the list. Thus there is no last or
end reference variable.
I don't know how to write this program :'( ..
I need your help guys and I will be so happy if anyone can do it for me ..
The sad girl
MaRia :(Any body can give me any idea any hint that may help
me ??Hint that will help you: get a personal tutor. This is the wrong place to learn how to program. And you definitely won't learn by having your homework done for you.
Oh, and I don't care at all that your hamster has diarrhea, your boyfriend broke up with you, both of your parents are dead and unemployed, that you have to look after your 231 siblings all by yourself and that you're forced to take this class and rather want to do something completely different.
Heard it all before. -
Hey people, i need a small help on my linked list.
Ok, what i'm trying to do is have a search function with a linked list using strings. First i will have a string, i will then compute the ASCII value for that and take MOD 71 lets say. For example, a string has an ASCII value of 216, MOD 71 of this gives me 3. I will then have an array of 71, and each array will point to a linked list. There will be as many linked list as there are of arrays (71). I will then store this string at index [3] in the linked list in which the array points to.
My problem for now is, how do i for example create 71 linked list? So far i can create only 1. To create another is easy, but if i have 71 the code will be too much. Is there an iterator i could use that easily creates 71? Sorry about this, i'm not really good with linked list with Java. Anyway, here is what i have now :).
public class MyLinkedListElement {
String string;
MyLinkedListElement next;
public MyLinkedListElement(String s) {
string = s;
next = null;
public MyLinkedListElement getNext() {
return next;
public String getValue() {
return string;
public class MyLinkedList {
public static MyLinkedListElement head;
public MyLinkedList() {
head = null;
public static void addToHead(String s) {
MyLinkedListElement a = new MyLinkedListElement(s);
if (head == null) {
head = a;
} else {
a.next = head;
head = a;
public static void main(String[] args) {
String[] arr = {"Bubble", "Angie", "Bob", "Bubble", "Adam"};
for (int i = 0; i < arr.length; i++) {
addToHead(arr);
MyLinkedListElement current = head;
while (current != null) {
System.out.println(current.getValue());
current = current.next;
}I can have an array of strings and easily add them to a linked list.I am very confused now, i just need to store a string value inside an array of linked list. But i can't somehow do it. I am very close, i can store the value in a linked list but the array of linked list, this is what i have.
public class MyLinkedListElement {
String string;
MyLinkedListElement next;
public MyLinkedListElement(String s) {
string = s;
next = null;
public MyLinkedListElement getNext() {
return next;
public String getValue() {
return string;
public class MyLinkedList {
public MyLinkedListElement head;
public MyLinkedList() {
head = null;
public void addToHead(String s) {
MyLinkedListElement a = new MyLinkedListElement(s);
MyLinkedList[] arrayOfLinkedLists = new MyLinkedList[71];
for(int i = 0; i < arrayOfLinkedLists.length; i++) {
arrayOfLinkedLists[i] = new MyLinkedList();
if (head == null) {
head = a;
} else {
a.next = head;
head = a;
public void print(MyLinkedListElement current) {
while (current != null) {
System.out.println(current.getValue());
current = current.next;
public static void main(String[] args) {
String[] arr = {"Bubble", "Angie", "Bob", "Bubble", "Adam"};
MyLinkedList listInstance = new MyLinkedList();
for (int i = 0; i < arr.length; i++) {
listInstance.addToHead(arr);
MyLinkedListElement current = listInstance.head;
listInstance.print(current); -
How do I find the smallest element of a doubly linked list?
I currently have a doubly link list, each node contains two datafields df1 and df2. I need to find the smallest of df2 contained in the list and swap it with index one - until the list is sorted.
Any ideas on how to search a doubly linked list for the smallest element would be greatly appreciated, thanks for your help.
ps: I have found methods for find an element in a list and tried to alter it to find smallest, but my dfs are objects and I am having difficulty with the comparison.
thanks so much for your time.I have given some comments in your other thread and instead of finding the minimum in each scan, you can do "neighbour-swaps". This will sort the list in fewer scans.
-
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(); -
Sort Linked List...
I need help sorting a linked list.
So far, in my sort method I have...
public LinkedList sort();
LinkedList newList = new LinkedList();
Node ref;
Node temp = new Node(head.getempID(); head.getempLast(), head.getempFirst(); head.getempDept(), head.getempSalary());
for(ref = head; ref != null; ref.getNext());
if(ref.getempID() <= temp.getEmpID());
temp = (ref.getempID(), ref.getempLast(), ref.getempFirst(), ref.getempDept(), ref.getempSalary());
newList.insert(temp); //???????
return newList();
// As you can tell, each one of my node's consists of an employee's id number, last name, first name, department, and salary...I need to sort the linked list by the employee's ID number. I can not figure out how to swap nodes though. PLEASE HELP A KID OUT!!!I was worng, my last data structure lecture today(I hope).
| | | | | | | | | |
head->| Node1 |---->| Node2 |---->| Node3 |---->| Node4 |---etc-->| NodeN |->null
| | | | | | | | | |
Q: How do you swap node2 with node3?
A: Think about it! Look at a picture if thats what you need. Draw the lines of reference to figure it out.
1. Where does node1.next need to point to, how about node2.next, or node3.next?
3. How do you change these without losing a node, are you going to need a temp?
4. What about special case(switching node1 and node2)?
This is simple problem solving skills. I assume you have built the list yourself,
so you have the basic knowledge base needed. -
Linked List bubbleSort problems
I'm trying to implement a bubbleSort (with a insertionSort and selectionSort) on a linked list, but can't seem to get it working. Any tips on correcting the bubbleSort, and maybe some for the other two? Thanks!!!
public class sortingMethods {
public sortingMethods() {}
public void bubbleSort(LinkedList list) {
if(list.isEmpty())
System.out.println("List is currently empty.");
else if (list.size() == 1)
System.out.println("List is already sorted.");
else {
Node current = list.getHead();
Node next = current.getNext();
Node temp;
int counter = 0;
boolean exchangeMade = true;
while(counter < (list.size() - 1) && exchangeMade) {
counter++;
exchangeMade = false;
for(int i = 1; i <= (list.size() - counter); i++) {
if(current.getData() > next.getData()) {
temp = current;
current = next;
next = temp;
exchangeMade = true;
public void selectionSort(LinkedList list) {
if(list.isEmpty())
System.out.println("List is currently empty.");
else if (list.size() == 1)
System.out.println("List is already sorted.");
else{}
public void insertionSort(LinkedList list){
if(list.isEmpty())
System.out.println("List is currently empty.");
else if (list.size() == 1)
System.out.println("List is already sorted.");
else {
public class LinkedList {
private Node head;
private int count;
public LinkedList() {
head = null;
count = 0;
public LinkedList(LinkedList rhs) { //Copy constructor
head = rhs.head;
count = rhs.count;
public void orderedInsert(int item) { //Inserts the Node in the right position - Ascending
Node back = null;
Node newNode = new Node(item);
Node pointer = head;
boolean found = false;
while(pointer != null && !found) {
if(pointer.getData() > item)
found = true;
else {
back = pointer;
pointer = pointer.getNext();
newNode.setNext(pointer);
if(back == null) {
head = newNode;
count++;
else {
back.setNext(newNode);
count++;
public void insert(int item) { //Inserts at front of list
Node newnode = new Node(item);
if(head == null)
head = newnode;
else {
newnode.setNext(head);
head = newnode;
public void orderedRemove(int item) { //Searches and removes selected Node
Node back = null;
boolean found = false;
Node pointer = head;
while(pointer != null && !found) {
if(pointer.getData() == item)
found = true;
else {
back = pointer;
pointer = pointer.getNext();
if(found)
if(back == null) {
head = pointer.getNext();
count--;
} else {
back.setNext(pointer.getNext());
count--;
} else
System.out.println("Data not found in list.");
public void remove() { //Removes from front of list
if(head == null)
System.out.println("List is currently empty.");
else {
Node n = head;
head = head.getNext();
n.setNext(null);
count--;
public boolean isEmpty() {
if(head == null)
return true;
else
return false;
public void print() {
Node current = head;
while(current != null) {
System.out.println(current.getData());
current = current.getNext();
public int size() {return count;}
public Node getHead() {return head;}
} //End LinkedList classI'm still having problems! Now the code just seems to go through an endless loop.
public void bubbleSort(LinkedList list) {
if(list.isEmpty())
System.out.println("List is currently empty.");
else if (list.size() == 1)
System.out.println("List is already sorted.");
else {
boolean exchangeMade = true;
int counter = 0;
Node current = list.getHead();
Node next = current.getNext();
Node temp;
while(counter < (list.size() - 1) && exchangeMade) {
counter++;
exchangeMade = false;
for(int i = 1; i <= (list.size() - counter); i++) {
if(current.getData() > next.getData()) {
temp = current;
current.setNext(next);
next.setNext(temp);
exchangeMade = true;
}And here is the rest of my code...
package cs321_assignment1;
public class LinkedList { //Doubly Linked List
private Node head;
private int count;
public LinkedList() {
head = null;
count = 0;
public LinkedList(LinkedList rhs) { //Copy constructor
head = rhs.head;
count = rhs.count;
public void orderedInsert(int item) { //Inserts the Node in the right position - Ascending
Node back = null;
Node newNode = new Node(item);
Node pointer = head;
boolean found = false;
while(pointer != null && !found) {
if(pointer.getData() > item)
found = true;
else {
back = pointer;
pointer = pointer.getNext();
newNode.setNext(pointer);
if(back == null) {
head = newNode;
count++;
else {
back.setNext(newNode);
count++;
public void insert(int item) { //Inserts at front of list
Node newnode = new Node(item);
if(head == null)
head = newnode;
else {
newnode.setNext(head);
head = newnode;
count++;
public void orderedRemove(int item) { //Searches and removes selected Node
Node back = null;
boolean found = false;
Node pointer = head;
while(pointer != null && !found) {
if(pointer.getData() == item)
found = true;
else {
back = pointer;
pointer = pointer.getNext();
if(found)
if(back == null) {
head = pointer.getNext();
count--;
} else {
back.setNext(pointer.getNext());
count--;
} else
System.out.println("Data not found in list.");
public void remove() { //Removes from front of list
if(head == null)
System.out.println("List is currently empty.");
else {
Node n = head;
head = head.getNext();
n.setNext(null);
count--;
public boolean isEmpty() {
if(count == 0)
return true;
else
return false;
public void print() {
Node current = head;
while(current != null) {
System.out.println(current.getData());
current = current.getNext();
public int size() {return count;}
public Node getHead() {return head;}
public void setHead(Node n) {head = n;}
} //End LinkedList class
package cs321_assignment1;
public class Node {
private int data;
private Node next;
public Node() {next = null;}
public Node(int d) {
next = null;
data = d;
public int getData() {return data;}
public void setData(int newData) {data = newData;}
public Node getNext() {return next;}
public void setNext(Node newNode) {next = newNode;}
}I can't figure this out, and I really need some help. Hopefully after I solve this, the selection and insertion sorts will be a little simpler. Any help will really be appreciated. -
Is my code a Linked Lists or not?
Hello everyone,
[I hope I am in the right forum]
I am trying to learn how to implement Linked Lists with Java. I have written a small code and I would appreceate it a lot if any one would be kind enough to check if this code is really a linked list.
I tried to make a list with 3 nodes, with no helping methods for adding and removing nodes. Just a simple example. This is my code:
public class myList{
public static final long serialVersionUID = 24362462L;
//node pointer important to define private, so not share same value
private myList pointer;
//node data
private String nodeData;
public static void main(String args[]){
//Give memory to nodes
myList Node1 = new myList();
myList Node2 = new myList();
myList Node3 = new myList();
//Make Node1
Node1.pointer = Node2;//give value to pointer
Node1.nodeData = "Hi i am data contained in Node 1.";
//Make Node2
Node2.pointer = Node3;
Node2.nodeData = "Hi i am data contained in Node 2.";
//Make Node3
Node3.pointer = null;
Node3.nodeData = "Hi i am data contained in Node 3.";
//Display Data
System.out.println(Node1.nodeData);
System.out.println(Node2.nodeData);
System.out.println(Node3.nodeData);
//Display pointers
System.out.println("Hi this is Node2 ==============>:"+Node2);
System.out.println("This is the value of pointer of Node1:"+Node1.pointer);
System.out.println("Hi this is Node3===============>:"+Node3);
System.out.println("This is the value of pointer of Node2:"+Node2.pointer);
}//main
}//class
/***** OUTPUT ***** OUTPUT ***** OUTPUT ***** OUTPUT *****
Hi i am data contained in Node 1.
Hi i am data contained in Node 2.
Hi i am data contained in Node 3.
Hi this is Node2 ========================>:myList@16f0472
This is the value of pointer of Node 1 ==>:myList@16f0472
Hi this is Node3 ========================>:myList@18d107f
This is the value of pointer of Node 2 ==>:myList@18d107f
Press any key to continue...
Thank you very much,
JMelsiHappy to advise. Here we go. :)
Firstly, you'll want to post your code in code tags. They make your code more legible, thus making it easier and therefore more likely that someone responds. ;)
Second, it would be more appropriate for class names (such as "myList") to start with an upper-case letter (such as "MyList"). Additionally, the class in question does not represent a whole list but instead a node, so you might want to call it "MyListNode" or something similar.
Strictly speaking, your code is definitely that of a linked list of nodes. For example, one could print all of the contents in your list with code like this:
myList node = ...; // assign to the first node
while (node!=null) // as long as there is a node
System.out.println(node.nodeData); // print the data in this node
node = node.pointer; // move on to the next node
}Note that, in the above code, I didn't have to know how many nodes were in your list or have any references to them beforehand. :) That's the power in the data structure you're creating.
Enjoy!
Maybe you are looking for
-
How to enter 3,46 and not have it change to 4 in CS5 bar chart?
Hi, I use CS5 (Win) and I want to be able to enter bar chart values less than whole numbers - like 3,46... when I write that it automatically changes to 4. How/where do I change the setting for this? Thanks in advance! Eva
-
How to view all the patches installed in a WebLogic
Hi All, Is there a way on how to view all the patches installed in a WebLogic Server particular the 10.3.1? Thanks, Ace
-
Magic mouse not working when my computer wakes up from sleep mode sometimes
This does not happen all the time but it is starting to happen more and more. When my iMac is asleep and I wake it up the mouse is non responsive. I have looked at the green indicator light on the magic mouse and it does not respond as well. I have t
-
Insufficient Access Rights when trying to modify send as permissions on a public folder
Where I work, we have 2 mailbox database servers and 2 cas servers on Exchange 2010, upgraded from Exchange 2003. We are finding that when trying to grant a user send as rights to a publlic folder we are getting an Insufficient Access Rights error. T
-
Hi All We had few performance issues in production box and after checks found that data area usage in LC was very high at 90% ,during peak load. So we have added 4gb ( two new data files of MAXDB ), now the system performance looks better and data a