Circular Linked List Help
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
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. -
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 -
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. -
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. -
Hey,
I am having trouble understanding the Linked List implementation code given under the Node Operations part of this pdf.
http://www.cs.berkeley.edu/~jrs/61b/lec/07.pdf
public ListNode(int item, ListNode next) {
this.item = item;
this.next = next;
public ListNode(int item) {
this(item, null);
ListNode l1 = new ListNode(7, new ListNode(0, new ListNode(6)));
I understand the earlier implementation, but this one has me confused. Would someone please go through/explain the flow of this implementation with me?
ThanksWell the code is pretty self explanitory.
a ListNode class that has two fields. an int field item, and a ListNode field next.
so when you create a ListNode object you can do so by one of two means passing one parameter or passing two parameters.
if you pass one parameter then you have a ListNode which has an int say 1 and a ListNode object who's value is null.
if you pass two parameters then you have a ListNode which has an int say 2 and a ListNode object who's value is the ListNode you pass to it.
ex ListNode myNode = ListNode(1,new ListNode(2));
so myNode now has an integer 1 and a reference to another ListNode which has an integer value of 2 and a reference to a null ListNode.
hope this helps. -
Hi,
I have an assignment on linked lists, as a beginner I am really struggling with it for hours...
I have to write the following methods without importing any libraries.
"Write an iterative method delete() for LinkedStackOfStrings that takes an integer parameter k and deletes the kth element (assuming it exists).
Write a method find() that takes an instance of LinkedStackOfStrings and a string key as arguments and returns true if some node in the list has key as its item field, false otherwise."
It must be implemented in the code on this site:
[http://www.cs.princeton.edu/introcs/43stack/LinkedStackOfStrings.java.html]
Help would be appreciated! I have been trying for hours :(vdL wrote:
Thanks for the reply! Yes, I forgot add what my actual problem is.
If I am correct, I will need to be able to traverse through the list up to a certain point, redirect and redirect the pointers.
My problem is I am able to traverse through the list using 'for(Node x = first; x != null; x= x.next)' but I do not know how make it only run up to a particular position in the list.You can keep an integer counter, increment it each time through the loop, and break out of the loop when the counter is big enough. Example of breaking:
if (n == k) break;
And also, how not to loose the previous Node when traversing trough the list.You're allowed to have multiple references. So you could keep one reference to the current node, and one reference to the one before it.
Or, rather than looping through the list until you find the kth element, loop until you find the (k - 1)th element, then (if it exists) remove the one after it. -
Hi, I am implementing a graph for my Java project and part of the coding requires link list for the edges.
I wrote the code, but I just don't understand why it does not function the way like it is in C++.
Bascilly, I have trouble adding data into a linklist
My codes are as follows:
public int insertLink(String fCity, String tCity, int distance)
int location = find(fCity);
if(location == -1)
return -1;
else
insertNode(new Link(tCity,distance), location);
return 0;
private void insertNode(Link node, int index)
Link head = vertex[index].head;
while(head != null)
head = head.next;
head = node;
This is to add stuff to the list, but for some reason, when i try to display the data, i keep getting null. somehow when
head = node
head = new Link(data, data);
the head points to somwhere else, and not refer to the linklist vertex[index].head anymore...
Here is my code to display my data:
public void printVertex()
for(int i = 0; i < vertex.length; i++)
if(vertex[i] != null)
System.out.print(vertex[i]+" --");
Link node = vertex.head;
while(node != null)
System.out.print(node.toCity+","+node.distance+"--");
node = node.next;
System.out.println();
Am i doing something wrong so my linklist isn't implement correct?
THank you.Hi, the "fix" for head.next != null didn't work
private void insertNode(Link node, int index)
Link head = vertex[index].head;
while(head != null)
head = head.next;
head = node;
System.out.println(head.toCity+","+head.distance);
System.out.println(vertex[index].head.toCity+","+vertex[index].head.distance);
}basiclly. When i do System.out.println(head.toCity+","+head.distance);, it can display data
but System.out.println(vertex[index].head.toCity+","+vertex[index].head.distance);
it throow null's error.
Btw, yes , i know Java have build in Link list, but unfortunately, my professor likes to reinvent the wheel and want us to do everything from scratch...
So any other help will be useful, thank you. -
Alphabetizing a linked list, HELP!
To all:
Firstly, I'm not looking for someone to do my assignment for me. I just need a push in the right direction...
I need to create a linked list that contains nodes of a single string (a first name), but that list needs to be alphabetized and that's where I am stuck.
I can use an iterator method that will display a plain-old "make a new node the head" linked list with no problem. But I'm under the impression that an iterator method is also the way to go in alphabetizing this list (that is using an iterative method to determine the correct place to place a new node in the linked list). And I am having zero luck doing that.
The iterator method looks something like this:
// ---- MyList: DisplayList method ----
void DisplayList()
ListNode p;
for (ResetIterator(); (p = Iterate()) != null; )
p.DisplayNode();
// ---- MyList: ResetIterator method ----
void ResetIterator()
current = head;
// ---- MyList: Iterate method ----
ListNode Iterate()
if (current != null)
current = current.next;
return current;
Can I use the same iterator method to both display the final linked list AND alphabetize my linked list or do I need to create a whole new iterator method, one for each?
Please, someone give me a hint where to go with this. I've spent something like 15 hours so far trying to figure this thing out and I'm just stuck.
Thanks so much,
John
[email protected]I'll try and point you in the right direction without being too explicit as you request.
Is your "linked list" an instance of the Java class java.util.LinkedList or a class of your own?
If it is the Java class, then check out some of the other types of Collections that provide built-in sorting. You should be able to easily convert from your List to another type of Collection and back again to implement the sorting. (hint: you can do this in two lines of code).
If this is your own class and you want to code the sort yourself, implement something simple such as a bubble sort (should be easy to research on the web).
Converting to an array, sorting that and converting back is another option.
Good Luck. -
I am fairly new to Java, and Linked Lists. Can you tell me how I can fix my code? Why does my code print infinite "3" s. That is all I am trying to do is create a linked list and put that linked list into index 2 of the array. In the loop, I am setting up a whole bunch on null Node's, is it even possible to link all these nodes together in that same loop? If something does not make sense, I will try to elaborate. I will eventually impliment an insert method in the Node class, are there any pointers on how to implement it? What are the special cases I need to be looking for when implementing the insert method?
* To change this template, choose Tools | Templates
* and open the template in the editor.
package testlinkedlist;
* @author Ben
public class Main {
* @param args the command line arguments
public static Node l;
public static Node p = new Node();
public static Node Front;
public static void main(String[] args) {
Node[] anArray = new Node[4];
for(int i = 0; i < 4; i++){
anArray[i] = new Node();
l = new Node(i);
l.setLink(l);
anArray[2] = l;
while(anArray[2] != null){
System.out.println(anArray[2].dataInNode());
anArray[2] = anArray[2].next;
}l = new Node(i);
l.setLink(l);The node l is created in line one, in line two a link is created from l to l. In other words here is the presence of your infinite loop which is magnified in the following piece of code:
anArray[2] = l;
while(anArray[2] != null){
System.out.println(anArray[2].dataInNode());
anArray[2] = anArray[2].next;
}Mel -
Linked lists help... how exactly is this a NullPointerException?
So I have a linked list class with variables head and tail both initialized to "null", with variables for size, declare, and traveler (not really relevant to this though). We have to create methods to manipulate said list.
For a test I declared an instance of this linked list:
static SinglyLinkedList list = new SinglyLinkedList();One of the methods we have to create is an append method, here's the code for that:
public void append(Object dataToAdd)
if(head == null & tail == null)
head = new Node(dataToAdd, null);
tail = head;
else
tail.next = new Node(dataToAdd, null);
tail = tail.next;
}Testing it with...
list.append("A");Gives null pointer exceptions at the if statement in the append method as well as at the list.append line. But why? What is exactly pointing to null?Ah... I didn't think of head not being null but tail being null.
I initiated the traveler node in the linked list class to head.
then I added this in between the if and else statements I had:
else if(head != null & tail == null)
while(traveler.next != null)
traveler = traveler.next;
tail = traveler;
tail.next = new Node(dataToAdd, null);
tail = tail.next;
}But it's still giving me the same errors.
Edited by: klawson88 on Feb 12, 2009 12:32 AM -
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 -
Need help regarding Linked List
I'm a beginner who just spent ages working on the following code.. but need help on re-implementing the following using a linked list, i.e. no array is allowed for customer records but you still can use arrays for names, address, etc.. Hopefully I've inserted enough comments..
Help very much appreciated!! Thanks! =]
import java.util.Scanner;
import java.io.*;
public class Bank
/* Private variables declared so that the data is only accessible to its own
class, but not to any other class, thus preventing other classes from
referring to the data directly */
private static Customer[] customerList = new Customer[30];
//Array of 30 objects created for storing information of each customer
private static int noOfCustomers;
//Integer used to store number of customers in customerList
public static void main(String[] args)
Scanner sc = new Scanner(System.in);
menu();
public static void menu()
char choice;
String filename;
int custId,counter=0;
double interestRate;
Scanner sc = new Scanner(System.in);
do
//Displaying of Program Menu for user to choose
System.out.println("ABC Bank Customer Management System Menu");
System.out.println("========================================");
System.out.println("(1) Input Data from File");
System.out.println("(2) Display Data");
System.out.println("(3) Output Data to File");
System.out.println("(4) Delete Record");
System.out.println("(5) Update Record");
System.out.println("(Q) Quit");
System.out.println();
System.out.print("Enter your choice: ");
String input = sc.next();
System.out.println();
choice = input.charAt(0);
//switch statement used to assign each 'selection' to its 'operation'
switch(choice)
case '1': int noOfRecords;
System.out.print("Enter file name: ");
sc.nextLine();
filename = sc.nextLine();
System.out.println();
noOfRecords = readFile(filename);
System.out.println(+noOfRecords+" records read.");
break;
case '2': displayRecords();
break;
case '3': writeFile();
break;
case '4': System.out.print("Enter account ID to be deleted: ");
sc.nextLine();
custId = sc.nextInt();
deleteRecord(custId);
break;
case '5': if(counter==0)
System.out.print("Enter current interest rate for saving account: ");
sc.nextLine();
interestRate = sc.nextDouble();
update(interestRate);
counter++;
else
System.out.println("Error: Accounts have been updated for the month.");
break;
}System.out.println();
}while(choice!='Q' && choice!='q');
/* The method readFile() loads the customer list of a Bank from a specified
text file fileName into customerList to be stored as array of Customer
objects in customerList in ascending alphabetical order according to the
customer names */
public static int readFile(String fileName)
int custId,i=0;
String custName,custAddress,custBirthdate,custPhone,custAccType;
double custBalance,curRate;
boolean d;
/* Try block to enclose statements that might throw an exception, followed by
the catch block to handle the exception */
try
Scanner sc = new Scanner(new File(fileName));
while(sc.hasNext())
/* sc.next() gets rid of "Account", "Id" and "=" */
sc.next();sc.next();sc.next();
custId = sc.nextInt();
d=checkDuplicate(custId);
/* checkDuplicate() is a method created to locate duplicating ids in array */
if(d==true)
/* A return value of true indicates duplicating record and the sc.nextLine()
will get rid of all the following lines to read the next customer's record */
sc.nextLine();sc.nextLine();sc.nextLine();
sc.nextLine();sc.nextLine();sc.nextLine();
continue;
/* A return value of false indicates no duplicating record and the following
lines containing the information of that customer's record is being read
in */
if(d==false)
/* sc.next() gets rid of "Name" and "=" and name is changed to upper case*/
sc.next();sc.next();
custName = sc.nextLine().toUpperCase();
/* sc.nextLine get rids of the following lines to read the next customer's
record if length of name is more than 20 characters*/
if(custName.length()>21)
System.out.println("Name of custId "+custId+" is more than 20 characters");
System.out.println();
sc.nextLine();sc.nextLine();sc.nextLine();sc.nextLine();
continue;
/* sc.next() gets rid of "Address" and "=" */
sc.next();sc.next();
custAddress = sc.nextLine();
/* sc.nextLine get rids of the following lines to read the next customer's
record if length of address is more than 80 characters*/
if(custAddress.length()>81)
System.out.println("Address of custId "+custId+" is more than 80 characters");
System.out.println();
sc.nextLine();sc.nextLine();sc.nextLine();sc.nextLine();
continue;
/* sc.next() gets rid of "DOB" and "=" */
sc.next();sc.next();
custBirthdate = sc.nextLine();
/* sc.nextLine get rids of the following lines to read the next customer's
record if length of date of birth is more than 10 characters*/
if(custBirthdate.length()>11)
System.out.println("D.O.B of custId "+custId+" is more than 10 characters");
System.out.println();
sc.nextLine();sc.nextLine();sc.nextLine();sc.nextLine();
continue;
/* sc.next() gets rid of "Phone", "Number" and "=" */
sc.next();sc.next();sc.next();
custPhone = sc.nextLine();
/* sc.nextLine get rids of the following lines to read the next customer's
record if length of phone number is more than 8 characters*/
if(custPhone.length()>9)
System.out.println("Phone no. of custId "+custId+" is more than 8 characters");
System.out.println();
sc.nextLine();sc.nextLine();sc.nextLine();sc.nextLine();
continue;
/* sc.next() gets rid of "Account", "Balance" and "=" */
sc.next();sc.next();sc.next();
custBalance = sc.nextDouble();
/* sc.next() gets rid of "Account", "Type" and "=" */
sc.next();sc.next();sc.next();
custAccType = sc.next();
if(custAccType.equals("Saving"))
customerList[noOfCustomers] = new Account1(custId,custName,custAddress,custBirthdate,custPhone,custBalance,custAccType);
sc.nextLine();
noOfCustomers++;
i++;
else if(custAccType.equals("Checking"))
customerList[noOfCustomers] = new Account2(custId,custName,custAddress,custBirthdate,custPhone,custBalance,custAccType);
sc.nextLine();
noOfCustomers++;
i++;
else if(custAccType.equals("Fixed"))
sc.next();sc.next();sc.next();sc.next();
curRate = sc.nextDouble();
Account3 temp = new Account3(custId,custName,custAddress,custBirthdate,custPhone,custBalance,custAccType,curRate);
customerList[noOfCustomers]=temp;
sc.nextLine();
noOfCustomers++;
i++;
else
System.out.println("Account type not defined.");
if(noOfCustomers==30)
System.out.println("The customer list has reached its maximum limit of 30 records!");
System.out.println();
return noOfCustomers;
//Exceptions to be caught
catch (FileNotFoundException e)
System.out.println("Error opening file");
System.exit(0);
catch (IOException e)
System.out.println("IO error!");
System.exit(0);
/* Bubblesort method used to sort the array in ascending alphabetical order
according to customer's name */
bubbleSort(customerList);
return i;
/* The method displayRecords() displays the data of the customer records on
screen */
public static void displayRecords()
int k;
/* Displaying text using the printf() method */
for(k=0;k<noOfCustomers;k++)
System.out.printf("Name = %s\n", customerList[k].getName());
System.out.printf("Account Balance = %.2f\n", customerList[k].getBalance());
System.out.printf("Account Id = %d\n", customerList[k].getId());
System.out.printf("Address = %s\n", customerList[k].getAddress());
System.out.printf("DOB = %s\n", customerList[k].getBirthdate());
System.out.printf("Phone Number = %s\n", customerList[k].getPhone());
String type = customerList[k].getAccType();
System.out.println("Account Type = " +type);
if(type.equals("Fixed"))
System.out.println("Fixed daily interest = "+((Account3)customerList[k]).getFixed());
System.out.println();
/* The method writeFile() saves the content from customerList into a
specified text file. Data is printed on the screen at the same time */
public static void writeFile()
/* Try block to enclose statements that might throw an exception, followed by
the catch block to handle the exception */
try
int i;
int n=0;
//PrintWriter class used to write contents of studentList to specified file
FileWriter fwStream = new FileWriter("newCustomers.txt");
BufferedWriter bwStream = new BufferedWriter(fwStream);
PrintWriter pwStream = new PrintWriter(bwStream);
for(i=0;i<noOfCustomers;i++)
pwStream.println("Account Id = "+customerList.getId());
pwStream.println("Name = "+customerList[i].getName());
pwStream.println("Address = "+customerList[i].getAddress());
pwStream.println("DOB = "+customerList[i].getBirthdate());
pwStream.println("Phone Number = "+customerList[i].getPhone());
pwStream.printf("Account Balance = %.2f\n", customerList[i].getBalance());
pwStream.println("Account Type = "+customerList[i].getAccType());
if(customerList[i].getAccType().equals("Fixed"))
pwStream.println("Fixed Daily Interest = "+((Account3)customerList[i]).getFixed());
pwStream.println();
n++;
//Closure of stream
pwStream.close();
System.out.println(+n+" records written.");
catch(IOException e)
System.out.println("IO error!");
System.exit(0);
//Deletes specified record from list
public static void deleteRecord(int id)
int i;
i=locate(id);
if(i==200)
//checking if account to be deleted does not exist
System.out.println("Error: no account with the id of "+id+" found!");
//if account exists
else
while(i<noOfCustomers)
customerList[i] = customerList[i+1];
i++;
System.out.println("Account Id: "+id+" has been deleted");
--noOfCustomers;
//Updates the accounts
public static void update(double interest)
int i,j,k;
double custBalance,addition=0;
for(i=0;i<noOfCustomers;i++)
if(customerList[i] instanceof Account1)
for(j=0;j<30;j++)
addition=customerList[i].getBalance()*interest;
custBalance=customerList[i].getBalance()+addition;
customerList[i].setBalance(custBalance);
else if(customerList[i] instanceof Account2)
continue;
else if(customerList[i] instanceof Account3)
for(j=0;j<30;j++)
addition=customerList[i].getBalance()*((Account3)customerList[i]).getFixed();
custBalance=customerList[i].getBalance()+addition;
customerList[i].setBalance(custBalance);
else
System.out.println("Account type not defined");
System.out.println("The updated balances are: \n");
for(k=0;k<noOfCustomers;k++)
System.out.printf("Name = %s\n", customerList[k].getName());
System.out.printf("Account Balance = %.2f\n", customerList[k].getBalance());
System.out.println();
/* ================== Additional methods ==================== */
/* Bubblesort method to sort the customerList in ascending alphabetical
order according to customer's name */
public static void bubbleSort(Customer[] x)
int pass, index;
Customer tempValue;
for(pass=0; pass<noOfCustomers-1; pass++)
for(index=0; index<noOfCustomers-1; index++)
if(customerList[index].getName().compareToIgnoreCase(customerList[index+1].getName()) > 0)
tempValue = x[index];
x[index] = x[index+1];
x[index+1]= tempValue;
/* Method used to check for duplicated ids in array */
public static boolean checkDuplicate(int id)
int i;
for(i=0;i<noOfCustomers;i++)
if(id == customerList[i].getId())
System.out.println("Account Id = "+id+" already exists");
System.out.println();
return true;
}return false;
/* Method to seach for account id in array */
public static int locate(int id)
int j;
for(j=0;j<noOfCustomers;j++)
if(customerList[j].getId()==id)
return j;
j=200;
return j;
import java.util.Scanner;
public class Customer
/* The following private variables are declared so that the data is only
accessible to its own class,but not to any other class, thus preventing
other classes from referring to the data directly */
protected int id;
protected String name,address,birthdate,phone,accType;
protected double balance;
// Null constructor of Customer
public Customer()
id = 0;
name = null;
address = null;
birthdate = null;
phone = null;
balance = 0;
accType = null;
/* The following statements with the keyword this activates the Customer
(int id, String name String address, String birthdate, String phone, double
balance) constructor that has six parameters of account id, name, address,
date of birth, phone number, account balance and assign the values of the
parameters to the instance variables of the object */
public Customer(int id, String name, String address, String birthdate, String phone, double balance, String accType)
//this is the object reference that stores the receiver object
this.id = id;
this.name = name;
this.address = address;
this.birthdate = birthdate;
this.phone = phone;
this.balance = balance;
this.accType = accType;
/* The following get methods getId(), getName(), getAddress(), getBirthdate(),
getPhone(), getBalance() return the values of the corresponding instance
properties */
public int getId()
return id;
public String getName()
return name;
public String getAddress()
return address;
public String getBirthdate()
return birthdate;
public String getPhone()
return phone;
public double getBalance()
return balance;
public String getAccType()
return accType;
/* The following set methods setId(), setName(), setAddress(), setBirthdate(),
setPhone and setBalance() set the values of the corresponding instance
properties */
public void setId (int custId)
id = custId;
public void setName(String custName)
name = custName;
public void setAddress (String custAddress)
address = custAddress;
public void setBirthdate (String custBirthdate)
birthdate = custBirthdate;
public void setPhone (String custPhone)
phone = custPhone;
public void setBalance (double custBalance)
balance = custBalance;
public void setAccType (String custAccType)
accType = custAccType;
class Account1 extends Customer
public Account1(int id, String name, String address, String birthdate, String phone, double balance, String accType)
super(id,name,address,birthdate,phone,balance,accType);
this.id = id;
this.name = name;
this.address = address;
this.birthdate = birthdate;
this.phone = phone;
this.balance = balance;
this.accType = accType;
class Account2 extends Customer
public Account2(int id, String name, String address, String birthdate, String phone, double balance, String accType)
super(id,name,address,birthdate,phone,balance,accType);
this.id = id;
this.name = name;
this.address = address;
this.birthdate = birthdate;
this.phone = phone;
this.balance = balance;
this.accType = accType;
class Account3 extends Customer
protected double fixed=0;
public Account3(int id, String name, String address, String birthdate, String phone, double balance, String accType, double fixed)
super(id,name,address,birthdate,phone,balance,accType);
this.id = id;
this.name = name;
this.address = address;
this.birthdate = birthdate;
this.phone = phone;
this.balance = balance;
this.accType = accType;
this.fixed = fixed;
public double getFixed()
return fixed;
Example of a customers.txt
Account Id = 123
Name = Matt Damon
Address = 465 Ripley Boulevard, Oscar Mansion, Singapore 7666322
DOB = 10-10-1970
Phone Number = 790-3233
Account Balance = 405600.00
Account Type = Fixed
Fixed Daily Interest = 0.05
Account Id = 126
Name = Ben Affleck
Address = 200 Hunting Street, Singapore 784563
DOB = 25-10-1968
Phone Number = 432-4579
Account Balance = 530045.00
Account Type = Saving
Account Id = 65
Name = Salma Hayek
Address = 45 Mexican Boulevard, Hotel California, Singapore 467822
DOB = 06-04-73
Phone Number = 790-0000
Account Balance = 2345.00
Account Type = Checking
Account Id = 78
Name = Phua Chu Kang
Address = 50 PCK Avenue, Singapore 639798
DOB = 11-08-64
Phone Number = 345-6780
Account Balance = 0.00
Account Type = Checking
Account Id = 234
Name = Zoe Tay
Address = 100 Blue Eyed St, Singapore 456872
DOB = 15-02-68
Phone Number = 456-1234
Account Balance = 600.00
Account Type = Saving1) When you post code, please use[code] and [/code] tags as described in Formatting tips on the message entry page. It makes it much easier to read.
2) Don't just post a huge pile of code and ask, "How do I make this work?" Ask a specific question, and post just enough code to demonstrate the problem you're having.
3) Don't just write a huge pile of code and then test it. Write a tiny piece, test it. Then write the piece that will work with or use the first piece. Test that by itself--without the first piece. Then put the two together and test that. Only move on to the next step after the current step produces the correct results. Continue this process until you have a complete, working program.
Maybe you are looking for
-
i have tried to put headphones into the jack on my phone and will no longer accept them as it did only yesterday so not happy with apple seem to have nothing but problems with their products already had to go back to this phone due to issues with the
-
How do I cancel a secondary & 3rd Apple ID & 2nd iCloud account?
KELoPV is Back! & Still having the same problems with "Manage My Account" - No One has had an answer for me ... Yet. I'm still hopeful. On 10 January, I wrote this community. I keep trying to get into My Apple ID to change a very old email, one that
-
Hi I downloaded reader for my MAC I can only open PDF's in Safari and not firefox what can I do to fix this??
-
Apple Mail not received as sent to Outlook
I am puzzled. I send a reply to an email, and the receiving party only receives what I typed, not their original email appended at the bottom. I highlighted the original post, which I thought meant it would be included. This is NOT an attachment, but
-
We have made a test application in j2me which sends sms. The mobile server is "nokia 6681". Following is the result when we send sms to various other mobile Nokia 1100 message come but content says 'message can't be displayed'. Nokia 3310 sms reaches