Circular linked list while loop
i have a circular linked list and i'd like a while loop to iterate though all of them. my problem is that it always excludes the last node. i know why, it's due to the fact that "current.next != alive" skips it from ever accessing the last node. i can't seem to solve it. note that the last node in the list points to the first node (alive):
while(current.next != alive )
prev = prev == null ? prev = alive : prev;
//identify the name with it's matching node
if(name.equals(current.name.toLowerCase()))
prev.next = current.next;
dead = current;
current = current.next;
dead.next = null;
while(dead.next != null)
dead = dead.next;
else
prev = current;
current = current.next;
}
//this class assists the client in managing a game of assassinations. it does so by providing options such as verifying a target's existence, getting the list of dead people, getting the lsit of alive people, and moving people from the alive to dead list
public class AssassinManager
private AssassinNode alive;
private AssassinNode alive_tail;
private AssassinNode dead;
//pre: must send a string array
//post: nodes are created
public AssassinManager(String[] names)
dead = null;
alive = new AssassinNode(names[0]);
AssassinNode current = alive;
System.out.println(names[0] + " is first, " + names[(names.length-1)] + " is last\n\n");
for(int i = 1; i < names.length; i++)
while(current.next != null)
current = current.next;
current.next = new AssassinNode(names);
alive_tail = current.next = new AssassinNode(names[(names.length - 1)], alive);
//post: outputs all the people still alive
public void printKillRing()
AssassinNode last = null, current = alive;
while(current.next!= alive)
System.out.println(current.name + " is stalking " + current.next.name);
last = current.next;
current = current.next;
System.out.println(current.name + " is stalking " + alive.name);
//post: outputs a list of the dead people
public void printGraveyard()
AssassinNode last = null, current = dead;
while(dead != null)
System.out.println(current.name + " was killed by " + current.killer);
last = current.next;
current = current.next;
//pre: must send a string name
//post: will return true/false depending on the input if the name is in the killing ring (alive)
public boolean killRingContains(String name)
AssassinNode current = alive;
name = name.toLowerCase();
while(current.next!= alive)
if(name.equals(current.name.toLowerCase()))
return true;
current = current.next;
return false;
//pre; must send a string name
//post: will return true/false if the name is in the graveyard list
public boolean graveyardContains(String name)
AssassinNode current = dead;
name = name.toLowerCase();
while(dead != null && current.next != null)
if(name.equals(current.name.toLowerCase()))
return true;
current = current.next;
return false;
//post: checks if game is over by seeing if there is more than 1 player
public boolean gameOver()
AssassinNode current = alive;
if(current.next == null)
return true;
return false;
//post: outputs the winner's name
public String winner()
AssassinNode current = alive;
if(current.next == null)
return alive.name;
return null;
//pre: must send a string name that exists is alive
//post: will remove the user from the alive list and add it to the killed list
public void kill(String name)
//check if person exists to remove them from alive list
if(killRingContains(name.trim()) == true)
AssassinNode prev = null, current = alive, dead = this.dead;
name = name.toLowerCase();
while(current != null)
System.out.println(current.name);
if(name.equals(current.name.toLowerCase()))
prev = prev == null ? alive_tail : prev;
prev.next = current.next;
//dead = dead == null ? current : dead;
//while(dead.next != null)
//dead = dead.next;
if(prev.next == alive)
break;
current = prev.next;
else
if(current.next == alive)
break;
prev = current;
current = current.next;
}Edited by: ixxalnxxi on Apr 27, 2008 12:58 AM
Similar Messages
-
I need help with circular linked list
Hi,
I need help with my code. when I run it I only get the 3 showing and this is what Im supposed to ouput
-> 9 -> 3 -> 7
empty false
9
empty false
3
-> 7
empty false
Can someone take a look at it and tell me what I'm doing wrong. I could nto figure it out.
Thanks.This is my code
/ A circular linked list class with a dummy tail
public class CLL{
CLLNode tail;
public CLL( ){
tail = new CLLNode(0,null); // node to be dummy tail
tail.next = tail;
public String toString( ){
// fill this in. It should print in a format like
// -> 3 -> 5 -> 7
if(tail==null)return "( )";
CLLNode temp = tail.next;
String retval = "-> ";
for(int i = 0; i < -999; i++)
do{
retval = (retval + temp.toString() + " ");
temp = temp.next;
}while(temp!=tail.next);
retval+= "";}
return retval;
public boolean isEmpty( ){
// fill in here
if(tail.next == null)
return true;
else{
return false;
// insert Token tok at end of list. Old dummy becomes last real node
// and new dummy created
public void addAtTail(int num){
// fill in here
if (tail == null)
tail.data = num;
else
CLLNode n = new CLLNode(num, null);
n.next = tail.next;
tail.next = n;
tail = n;
public void addAtHead(int num){
// fill in here
if(tail == null)
CLLNode l = new CLLNode(num, null);
l.next = tail;
tail =l;
if(tail!=null)
CLLNode l = new CLLNode(num, null);
tail.next = l;
l.next = tail;
tail = l;
public int removeHead( ){
// fill in here
int num;
if(tail.next!= null)
tail = tail.next.next;
//removeHead(tail.next);
tail.next.next = tail.next;
return tail.next.data;
public static void main(String args[ ]){
CLL cll = new CLL ( );
cll.addAtTail(9);
cll.addAtTail(3);
cll.addAtTail(7);
System.out.println(cll);
System.out.println("empty " + cll.isEmpty( ));
System.out.println(cll.removeHead( ));
System.out.println("empty " + cll.isEmpty( ));
System.out.println(cll.removeHead( ));
System.out.println(cll);
System.out.println("empty " + cll.isEmpty( ));
class CLLNode{
int data;
CLLNode next;
public CLLNode(int dta, CLLNode nxt){
data = dta;
next = nxt;
}I'm not going thru all the code to just "fix it for you". But I do see one glaringly obvious mistake:
for(int i = 0; i < -999; i++)That says:
1) Initialize i to 0
2) while i is less than -999, do something
Since it is initially 0, it will never enter that loop body. -
Help Implementing a queue as a circular linked list...
I have a set of code that I need to implement a circular linked list into, but I am not sure how to approach it at all. If anyone can point me to some pseudo code or sample code that I can modify for my use, that would be great.
I created a Class CircularQueue, which implements Queue, I just need to figure out how to write it.
Heres the code I have:
Queue Interface
public interface Queue<ElementType> {
public void enqueue(ElementType e);
public ElementType dequeue();
public ElementType front();
public boolean isEmpty();
Data Holder
public class DataHolder<ElementType> {
// instance variables
private ElementType _data;
* Constructor for objects of class DataHolder
public DataHolder() {
_data = null;
public void setContents(ElementType anItem) {
_data = anItem;
public ElementType getContents() {
return _data;
DeqeueButton
import javax.swing.*;
import java.awt.event.*;
public class DequeueButton extends JButton {
// instance variables
private Queue<SmartRectangle> _queue;
private QueuePanel _queuePanel;
* Constructor for objects of class DequeueButton
public DequeueButton(QueuePanel aQueuePanel) {
super("Dequeue");
_queuePanel = aQueuePanel;
_queue = aQueuePanel.getQueue();
this.addActionListener(new DequeueButtonListener());
private class DequeueButtonListener implements ActionListener {
private final int MOVE_LENGTH = 25; // square size + 5
public void actionPerformed(ActionEvent e) {
_queue.dequeue(); // remove item from queue
_queuePanel.repaint();
EnqueueButton
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class EnqueueButton extends JButton {
// instance variables
private Queue<SmartRectangle> _queue;
private QueuePanel _queuePanel;
* Constructor for objects of class EnqueueButton
public EnqueueButton(QueuePanel aQueuePanel) {
super("Enqueue");
_queuePanel = aQueuePanel;
_queue = _queuePanel.getQueue();
this.addActionListener(new EnqueueButtonListener());
private class EnqueueButtonListener implements ActionListener {
private int _nextX, _nextY;
private final int SQUARE_SIZE = 20;
private final int MAX_X = 550;
private final int MAX_Y = 350;
private Color _currentColor;
public EnqueueButtonListener() {
_currentColor = Color.BLUE;
_nextX = MAX_X;
_nextY = MAX_Y;
public void actionPerformed(ActionEvent e) {
_queue.enqueue(new SmartRectangle(_nextX, _nextY, SQUARE_SIZE, SQUARE_SIZE, _currentColor, _queuePanel));
this.changeColor();
_nextX -= (SQUARE_SIZE+5); // location of next square in line
if (_nextX < 0) // if we reach edge of window, wrap
{ _nextY -= (SQUARE_SIZE+5);
_nextX = MAX_X;
if (_nextY < 0) // start over
_nextY = MAX_Y;
_queuePanel.repaint();
public void changeColor() {
if (_currentColor == Color.BLUE)
_currentColor = Color.RED;
else if (_currentColor == Color.RED)
_currentColor = Color.GREEN;
else if (_currentColor == Color.GREEN)
_currentColor = Color.YELLOW;
else if (_currentColor == Color.YELLOW)
_currentColor = Color.BLACK;
else if (_currentColor == Color.BLACK)
_currentColor = Color.BLUE;
FrontButton
import javax.swing.*;
import java.awt.event.*;
public class FrontButton extends JButton {
// instance variables
private Queue<SmartRectangle> _queue;
private QueuePanel _queuePanel;
* Constructor for objects of class DequeueButton
public FrontButton(QueuePanel aQueuePanel) {
super("Front");
_queuePanel = aQueuePanel;
_queue = aQueuePanel.getQueue();
this.addActionListener(new FrontButtonListener());
private class FrontButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
SmartRectangle rectangle = _queue.front(); // remove item from queue
SmartRectangle displayRect = _queuePanel.getDisplayFrontRect();
if (rectangle != null)
displayRect.setColor(rectangle.getColor());
_queuePanel.repaint();
QueueApp
import javax.swing.*;
import java.awt.*;
public class QueueApp extends JFrame
* Constructor for objects of class QueueApp
public QueueApp(String title)
super(title);
this.setSize(600,450);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
QueuePanel queuePanel = new QueuePanel();
javax.swing.JPanel buttonPanel = new JPanel(new FlowLayout());
buttonPanel.add(new EnqueueButton(queuePanel));
buttonPanel.add(new DequeueButton(queuePanel));
buttonPanel.add(new FrontButton(queuePanel));
this.add(queuePanel, BorderLayout.CENTER);
this.add(buttonPanel, BorderLayout.SOUTH);
this.setVisible(true);
public static void main (String [] args)
QueueApp app = new QueueApp("Queues at work: Object Oriented implementation.");
QueuePanel
import javax.swing.*;
import java.awt.*;
public class QueuePanel extends javax.swing.JPanel {
// instance variables
private Queue<SmartRectangle> _queue;
private SmartRectangle _frontRect;
* Constructor for objects of class QueuePanel
public QueuePanel() {
super();
_queue = new CircularQueue<SmartRectangle>();
_frontRect = new SmartRectangle(50,50,20,20,Color.WHITE, this);
public Queue<SmartRectangle> getQueue() {
return _queue;
public SmartRectangle getDisplayFrontRect() {
return _frontRect;
public void paintComponent(Graphics aBrush) {
super.paintComponent(aBrush);
Graphics2D aBetterBrush = (Graphics2D) aBrush;
Queue<SmartRectangle> tempQueue = new CircularQueue<SmartRectangle>();
if (_frontRect.getColor() != this.getBackground())
_frontRect.fill(aBetterBrush);
while (!_queue.isEmpty()) { // remove and display contents
SmartRectangle rectangle = _queue.dequeue();
rectangle.fill(aBetterBrush);
tempQueue.enqueue(rectangle);
while (!tempQueue.isEmpty()) { // put contents back into _queue
_queue.enqueue(tempQueue.dequeue());
_frontRect.setColor(this.getBackground());
SmartNode
public abstract class SmartNode<ElementType> {
public abstract boolean isEmpty();
public abstract SmartNode<ElementType> dequeue(DataHolder<ElementType> aHolder);
public abstract void front(DataHolder<ElementType> aHolder);
public void enqueue(ElementType anItem){}
public void setNext(SmartNode<ElementType> aNode) {
} // override as needed
public void setPrev(SmartNode<ElementType> aNode) {
} // override as needed
SmartRectangle
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
public class SmartRectangle extends Rectangle2D.Double {
// instance variables
private JPanel _panel;
private Color _color;
* Constructor for objects of class SmartRectangle
public SmartRectangle(int x, int y, int aWidth, int aHeight, Color aColor,
JPanel aPanel) {
super(x, y, aWidth, aHeight);
_panel = aPanel;
_color = aColor;
public void setLocation (int x, int y) {
this.setFrame(x, y, this.getWidth(), this.getHeight());
public Color getColor() {
return _color;
public void setColor(Color aColor) {
_color = aColor;
public void fill(Graphics2D aPaintBrush) {
Color savedColor = aPaintBrush.getColor();
aPaintBrush.setColor(_color);
aPaintBrush.fill(this);
aPaintBrush.setColor(savedColor);
}> Yea I think I understand the concept of it, but I
dont know what the code is supposed to look like.
Showing you what the code is supposed to look like would be effectively giving you the answer, which kind of defeats the purpose of "extra credit". Have you tried anything so far? Post what you've got, and we can give you hints on how to work through it. I thought some of the descriptions here were very explicit hints, but if you need some additional guidance, let us know your specific questions (other than "show me the code").
Good luck!
~ -
Hello,
I am working with circular linked Lists. Now the thing is that my assignment was to make this. I had to write a set of methods. Now the thing is that I had to write a method that removes the last value. I made it but it doesnt wark and also i am confused
public Object removeFirst()
if(size()==0)
return "empty list";
Object temp = last.getNext().getValue();
last.setNext(last.getNext().getNext());
size--;
return temp;
//doesnt Work
public Object removeLast()
public Object removeLast()
if (size()==0)
return "empty list";
Object temp= null;
temp = last.getNext().getValue();
last = last.getNext();
size--;
return temp;
}Well what is wrong with the code?
Does it compile?
Does it throw an error at runtime?
Does it give you an unexpected answer?
For solving problems like this with next/prev "pointers" I find diagramming boxes with arrows to help understand is an absolute requirement. Try figuring it out on paper.
If you are removing the last item in the list, that means that the item directly before this one, has to the next one in the list
Assuming you have a structure like this:
...--> (n-1) --> (n) --> (1) --> (2) -->...(n-1)Then removing item (n) you have to make (n-1) point at item (1) as item (n-1) becomes the new "last"
So you have to have the item before the "last" element to keep the next/prev pointers correct. -
Hi,
I'm developing a circular linked list class.. However everytime I add to the front of the list it overwrites the first element in the list.. I pretty confused at the moment. If anyone could assist me in what I'm doing wrong it would be greatly appreciated..
My Class:
public class CNode<T>
public T nodeValue; //data held by the node
public CNode<T> next; //next node in the list
//default constructor; next references node itself
public CNode()
nodeValue = null;
next = this;
//constructor; initializes nodeValue to item
//and sets the next to reference the node itself
public CNode(T item)
nodeValue = item;
next = this;
}My addFirst:
public static <T> void addFirst(CNode<T> header, T item)
CNode<T> curr;
CNode<T> newNode = new CNode<T>(item);
//header.next = newNode;
//newNode.next = header;
curr = header;
newNode.next = header;
curr.next = newNode;
}You need a Node class and a class that manages the nodes. The class the manages the nodes is typically called something like MyLinkedList. The MyLinkedList class will typically have a member called 'head' or 'first' and another member called 'last', 'end', or 'tail'. Those members will contain references to the first node and the last node respectively.
The methods like add(), remove(), find(), etc. will be members of the MyLinkedList class--not the Node class. The add() method of the MyLinkedList class will create a node, set the value of the node, and then set the next member to refer to the proper node or null if the node is added to the end of the list. Therefore, there is really no need for a default constructor in the node class. The MyLinkedList class will always set the value of the node, and then set it's next member to refer to something.
You might want to try to write a linear linked list first, and get that working, and then modify it to make it a circular linked list. In addition, you should be drawing pictures of nodes with arrows connecting the different nodes to understand what's going on. Whenver the next member of a node refers to another node, draw an arrow starting at the next member and ending at the node it refers to. The pictures will be especially helpful when you write functions like add().
Message was edited by:
7stud -
How to use circular linked list in pl/sql?
Hi all,
how to use the circular linked list on pl/sql programming.
thanks in advance
Rgds,
B@L@d balamurugan wrote:
Hi,
I needed this concept for the below example
TABLE_A have the columns of
ID COL_1 COL_2 COL_3 COL_4 COL_5 COL_6 COL_7
1....Y.........N........N.........Y........ N........N........ N
2....N.........N....... N.........Y.........N........N.........Y
in the above data
for id 1 i will need to take the value for COL_4, then i will check the next availability of Y through out through out the remaining columns, so next availability is on COL_1 so, i need to consider COL_4 which already Y and also i need to consider COL_5, COL_6, COL_7 as Y.
for id 2 if i need COL_7 then i need to come back on circular way and need to check the next availability of Y and need to take the columns having N before the next availability of YAnd... even after all that description... you haven't given any indication of what the output should look like.
Taking a wild guess on my part... something like this would do what you appear to be asking...
SQL> ed
Wrote file afiedt.buf
1 with t as (select 1 as id, 'Y' as col1, 'N' as col2, 'N' as col3, 'Y' as col4, 'N' as col5, 'N' as col6,'N' as col7 from dual union all
2 select 2, 'N', 'N', 'N', 'Y', 'N', 'N', 'Y' from dual)
3 --
4 -- END OF TEST DATA
5 --
6 select id
7 ,rcol
8 ,case when instr(cols,'Y',rcol+1) = 0 then instr(cols,'Y')
9 else instr(cols,'Y',rcol+1)
10 end as next_Y_col
11 from (select id, rcol, col1||col2||col3||col4||col5||col6||col7 as cols
12 from t, (select &required_col as rcol from dual)
13 where id = &required_id
14* )
SQL> /
Enter value for required_col: 4
old 12: from t, (select &required_col as rcol from dual)
new 12: from t, (select 4 as rcol from dual)
Enter value for required_id: 1
old 13: where id = &required_id
new 13: where id = 1
ID RCOL NEXT_Y_COL
1 4 1
SQL> /
Enter value for required_col: 7
old 12: from t, (select &required_col as rcol from dual)
new 12: from t, (select 7 as rcol from dual)
Enter value for required_id: 2
old 13: where id = &required_id
new 13: where id = 2
ID RCOL NEXT_Y_COL
2 7 4
SQL>If that's not what you want... then it's time you started learning how to ask questions properly. -
//would anyone know how to sort this, tried to put in a bubble sort but i got some many errors i deleted it
import uuInOut;
class studentlist
public static void main(String [] args)
final int LENGTH = 10; //the length of the list
//declare variables
String name, temp3, searchName;
int age, id, current;
boolean present = false;
//create new linked list
LinkedList list = new LinkedList();
//open data
uuTextFile data = new uuTextFile("data.txt");
data.OpenInputFile();
//add data from data file to the linked list
while (!data.EOF)
name = data.ReadString();//read name
age = data.ReadInt();//read age
id = data.ReadInt();//read id
//new instance of studentrecord to add to list
StudentRecord temp = new StudentRecord(name, age, id);
list.insert(0, temp);//add to list
//Print The whole list
for (int x = 0; x < list.length(); x ++)
StudentRecord temp2 = (StudentRecord)list.elementAt(x);
temp2.printdetails();
System.out.println("First in list: ");
StudentRecord First = (StudentRecord)list.getHead().getElement();
First.printdetails();//print the first entered in the list
System.out.println("Last in List: ");
int x = list.length() - 1;
StudentRecord Last = (StudentRecord)list.elementAt(x);
Last.printdetails();//print the last entered in the list
System.out.println("Please Enter Current Position: ");
current = uuInOut.ReadInt();
StudentRecord next = (StudentRecord) list.elementAt(current + 1);
next.printdetails();//prints the next position in the list
System.out.println("Please Enter Name: ");
temp3 = uuInOut.ReadString();//reads in a name to search for in the list
//loop to search through the list for the name entered
for (int j = 0; j < list.length(); j++){
StudentRecord temp4 = (StudentRecord)list.elementAt(j);
searchName = temp4.getname();
if (temp3.equals(searchName))
present = true;
System.out.println(present);
if (present == true)
System.out.println("Student Name Found");
else System.out.println("Not in list" );
}You could scrap this implementation and use a Collection class, then use Collections.sort. Or you could have your implementation implement the List interface and use Collections.sort. But more than likely you are supposed to do this for homework, so in that case I would try to implement the bubble sort and fix it until you don't get any errors. There are other sort routines you could use, but they are all more complicated than the bubble sort, so you will likely get many errors doing that too.
Good luck
Lee -
Hello,
I have a simple linked link. How do I save the entire list into a file, and and how to I restore the entire link list back into the program so that I can use it normally again?
I guess Serialization is used?
I don't want to save save all the filds in a file, then "re create" the link list by loops etc.Since Serialization saves the object in question and all the objects it references, if you make you're liunked list element Serializable and then save the first element, the Serialization process will save the entire list.
To get it back, read an Object from the file, it will be the first element of your list and its next link will point at the next element, etc.
If you have a circular list, this still works since the Serialization process will recognice that your saving the same object a second time and only send a reference. -
Hi guys!
I read the manual of java 2 and says that is not that pointers don't exist, they do exist but they are not explicit as they are in C languagge. So in need to create a circular linked list how can I do this? The instructions of the manual are not so clear. Does anyone have an idea and can give me a sample code?
Thanks to all
MaddyReferences are like pointers except that you cannot make any add operation on them. But you can of course change their values to make it point to other objects.
This also means that you can create graph objects and every data structure you like. For example :
class BinaryNode {
public Object data;
public BinaryNode left;
public BinaryNode right;
}To create binary trees or
class GraphNode {
public Object data;
public ArrayList links;
}Where links is a Java list containing a list of links (references) to other GraphNode.
Matthieu -
Turning a linked list into a for loop
Im stupid and cannot figure out how to make this
lp list1 = new lp(0,new lp(1, new lp(2, new lp(3, new lp(4, new lp(5, new lp(6, new lp(7, new lp(8, new lp(9, null))))))))));
into a for loop, i know its simple, i finished my first linked list assignmenet but having this in my program is too ugly and i know a loop should fix itJosAH wrote:
cotton.m wrote:
Ip list = new IP(9,null);
for(int i descending order starting from 8 and going down to zero)
list = new Ip(i,list);
That last/first element can be in the loop too:
Ip list = null;
for(int i descending order starting from 9 and going down to zero)
list = new Ip(i,list);
}kind regards,
Josd'oh! Yes that's better. Thanks. -
Hello,
is it possible to link while loops
ie. if i had two separate while x1 and x2 loops
when the start button is pushed only x1 starts.
is it possible when a condition is met (true) in x1 then x1 stops and x2 starts?
or is there a equivalant solution that is normally used in this case?
ThanksYes. Just run a wire from inside the first loop to the second loop. LabView will wait until the first loop is complete before executing the second.
Attachments:
DataDependency.png 5 KB -
If the circular double linked list has only one item, will that item's next/previous node references point to itself?
Yeah, it would make sense. But I'm wondering if there's any standard?
It could also make sense for the references to simply be null. -
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 -
Constructing a linked list from an array of integers
How do I create a linked list from an array of 28 integers in a constructor? The array of integers can be of any value that we desire. However we must use that array to test and debug methods such as getFirst(), getLast(), etc...
I also have a method int getPosition(int position) where its suppose to return an element at the specified position. However, I get an error that says cannot find symbol: variable data or method next()
public int getPosition(int position){
LinkedListIterator iter=new LinkedListIterator();
Node previous=null;
Node current=first;
if(position==0)
return current.data;
while(iter.hasMore()){
iter.next();
if(position==1)
return iter.data;
iter.next();
if(position==2)
return iter.data;
iter.next();
if(position==3)
return iter.data;
iter.next();
if(position==4)
return iter.data;
iter.next();
if(position==5)
return iter.data;
iter.next();
if(position==6)
return iter.data;
iter.next();
if(position==7)
return iter.data;
iter.next();
if(position==8)
return iter.data;
iter.next();
if(position==9)
return iter.data;
iter.next();
if(position==10)
return iter.data;
iter.next();
if(position==11)
return iter.data;
iter.next();
if(position==12)
return iter.data;
iter.next();
if(position==13)
return iter.data;
iter.next();
if(position==14)
return iter.data;
iter.next();
if(position==15)
return iter.data;
iter.next();
if(position==16)
return iter.data;
iter.next();
if(position==17)
return iter.data;
iter.next();
if(position==18)
return iter.data;
iter.next();
if(position==19)
return iter.data;
iter.next();
if(position==20)
return iter.data;
iter.next();
if(position==21)
return iter.data;
iter.next();
if(position==22)
return iter.data;
iter.next();
if(position==23)
return iter.data;
iter.next();
if(position==24)
return iter.data;
iter.next();
if(position==25)
return iter.data;
iter.next();
if(position==26)
return iter.data;
iter.next();
if(position==27)
return iter.data;
iter.next();
if(position==28)
return iter.data;
if(position>28 || position<0)
throw new NoSuchElementException();
}How do I create a linked list from an array of 28 integers
in a constructor? In a LinkedList constructor? If you check the LinkedList class (google 'java LinkedList'), there is no constructor that accepts an integer array.
In a constructor of your own class? Use a for loop to step through your array and use the LinkedList add() method to add the elements of your array to your LinkedList.
I get an error that
says cannot find symbol: variable data or method
next()If you look at the LinkedListIterator class (google, wait for it...."java LinkedListIterator"), you will see there is no next() method. Instead, you typically do the following to get an iterator:
LinkedList myLL = new LinkedList();
Iterator iter = myLL.iterator();
The Iterator class has a next() method. -
A linked list question.
So, I believe I understand linked lists for the most part, except for two lines....
boolean add(Transaction item)
for (Transaction curr = first; curr != null; curr = curr.next)
if (curr.part_num == item.part_num)
return false;
Transaction newItem = new Transaction();
newItem.transcode = item.transcode;
newItem.description = item.description;
newItem.part_num = item.part_num;
newItem.quantity = item.quantity;
newItem.next = first;
first.next = newItem;
return true;
}first is null, so First.next would be the first available space for actual insertion, and this is why it then puts null as newItem.next (the end of the list), and sticks newItem in first.next?
Im glad I read that pass by value thing earlier at the Java Ranch place...
Heres my actual question: When newItem.next = first; is called, it just copies null as the next field, but leaves the null in first alone right? And then it takes first.next and makes newItem copy into that field, thus inserting the first real item in the list?
Please tell me I made that connection right. :-D
Thanks!!Pictures are worth a hundred words with linked lists. Did you even put a pencil and paper next to your computer while doing this program, so that you could draw what is happening when you get confused?
If first is null, then the for loop is skipped--because first is assigned to curr and the loop only executes when curr is not equal to null.
So, this happens:
newItem = new Transaction()
int Transcode = 0
String description = null
int partNumber = 0
int quantity = 0
Tranasaction next = nullThen values are assigned to each field:
newItem
int Transcode = 10
String description = "screw"
int partNumber = 46
int quantity = 200
//freeze execution here:
Tranasaction next = null (what will happen here??)Your assumption was:
Transaction first = null
That means first does not refer to a Transaction object. Therefore, first does not have a description member, a quantity member, etc., and this is what things look like just before newItem.next = first; is executed:
newItem ----> Transaction
int Transcode = 10
String description = "screw"
int partNumber = 46
int quantity = 200
Tranasaction next = null
first ------> nullNow,
When newItem.next = first; is calledthings change to this:
newItem ----> Transaction
int Transcode = 10
String description = "screw"
int partNumber = 46
int quantity = 200
/-------Tranasaction next
first ------> null That isn't what you want. When you add() a Transaction object to the end of your linked list, it's next member should be null. It's the end of the chain, so there is no next.
And then it takes first.next and makes newItem copy
into that field, thus inserting the first real item in the
list?No. first is null so it does not refer to a Transaction object, and therefore there is no next member variable and consequently no such thing as first.next. You need to understand that null and a Transaction object that has 0 for every member are not the same.
But suppose for a minute that null and a Transaction object with zeros for every field were the same thing, so that first.next existed. If that was the case, then you could assign newItem to first.next. But, then you would be left with this:
first
int Transcode = 0
String description = null
int partNumber = 0
int quantity = 0
Tranasaction next = newItemWould you want the first Transaction object in your LinkedList to be almost entirely empty?
Instead, if first is null, you want to make first refer to newItem, i.e. you want to do this:
newItem ----> Transaction
int Transcode = 10
String description = "screw"
int partNumber = 46
int quantity = 200
Tranasaction next = null
first ----/ nullThen when the add() method ends, since newItem is a local variable, it will be destroyed leaving you with this:
Transaction
int Transcode = 10
String description = "screw"
int partNumber = 46
int quantity = 200
Tranasaction next = null
first ----/ null
Maybe you are looking for
-
Help with creating a new window
Hi there Could anyone help me with the coding to create a new window in java? Basically its when i click on a button a new window pops up thanks
-
How to structure the internal table issue I want to download to excel
Hi , I am trying to download the data from the internal table whose structure was i HAVE ONE INTERNAL TABLE WHICH IS 123 ABC MIKE 123 ABC DALLAS 123 ABC BOMBAY 345 BCD MEENAL 345 BCD SHINDE 345 BCD UJWALA I want the output the i WANT THE INTERNAL TAB
-
Changing the Site URL of a Sharepoint site changes the content type order
Description Changing the Site URL of a Sharepoint site changes the content type order of all lists that * contain folder content types * and have a custom content type order * where a folder content type is the first content type in order. Reproducib
-
When printing, how do I remove the invisible border off the edges of the paper?
-
1Gb Media Card Wont Be Recognized As Present Anymore
Ok i have a 1Gb Media Card in my Pearl and it was working fine up to the time i took it out one day and now my phone says its not present anymore...i tried putting an other media card in there and the other card works so i dont unerstand why this one