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!
~

Similar Messages

  • 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

  • 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.

  • Circular Linked List

    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.

  • How  to Implement a Chained Hash Table with Linked Lists

    I'm making a migration from C/C++ to Java, and my task is to implement a Chained Hash Table with a Linked List. My problem is to put the strings(in this case names) hashed by the table using de Division Metod (H(k)= k mod N) in to a Linked list that is handling the colisions. My table has an interface implemented(public boolean insert(), public boolean findItem(), public void remove()). Any Help is needed. Thanks for everyone in advance.

    OK. you have your hash table. What you want it to do is keep key/value pairs in linked lists, so that when there is a collision, you add the key/value pair to the linked list rather than searching for free space on the table.
    This means that whenever you add an item, you hash it out, check to see if there is already a linked list and if not, create one and put it in that slot. Then in either case you add the key/value pair to the linked list if the key is not already on the linked list. If it is there you have to decide whether your requirements are to give an error or allow duplicate keys or just keep or modify one or the other (old/new).
    When you are searching for a key, you hash it out once again and check to see if there is a linked list at that slot. If there is one, look for the key and if it's there, return it and if not, or if there was no linked list at that slot, return an error.
    You aren't clear on whether you can simply use the provided linked-list implementations in the Java Collections or whether you have to cobble the linked list yourself. In any case, it's up to you.
    Is this what you're asking?
    Doug

  • Anyone help me please~ many thanks! C++ linked list

    I've written a Microsoft C++ code, using a linked list to store the result which is sent by a device.
    The head node and tail node of linked list is put into a class, and all methods are set to 'static' to manipulate the data inside the linked list. So that different thread can access to it.
    At first, everything runs ok in native environment,( i compile it as a .exe file)....
    However, when I export it into DLL and run inside java code using JNI. The linked list was gone (head node & tail node lost). It seems that JVM try to re-initialize the head node everytime I invoke those method.
    Hence, I modify the class which handle the link list, set all its methods into non-static, and define a global variable. Yet, another problem came out... Acess Violation error... it seems again the adress(pointer) of head node can't be modified...
    Is there any other way to solve this problem?? I mean, I want the head node remains valid for each time of java method is called.

    Too vague.
    If you could show us some relevant Java and JNI C++
    code.
    Please paste your code between code tags exactly like
    this:
    your codeYou may read the [url
    http://forum.java.sun.com/help.jspa?sec=formatting]For
    matting tips for more information.Here you are:
    this is the header definition of the linked list handler, all functions are set to be non-static
    typedef struct DeviceLinkList{
        char *deviceNumber;//device of monitor device
        int result;
        DeviceLinkList *nextNode;
        DeviceLinkList *prevNode;
    } DeviceLinkList;
    class DeviceListHandler
    public:
      DeviceLinkList *headNode = NULL;
      DeviceLinkList *tailNode = NULL; //Moving to last of the entry
      void addNode(char *device); //add monitor device
      void deleteNode(char *device); //remove after device is stop monitorred
      void printAll();
      void setResult(char *device);
    private:
      DeviceLinkList *searchNode(char *device);
    };Here is the implementation of my code in function 'addNode':
    void DeviceListHandler::addNode(char *device)
      printf("Creating Link List.\n");
      printf("Head is %d\n" ,headNode);
      if(headNode != NULL) //create new node from empty --> Access Violation Exception start from here
        DeviceLinkList *temp = new DeviceLinkList;
        temp->deviceNumber = device;
        temp->nextNode = NULL;
        temp->prevNode = tailNode;
        tailNode->nextNode = temp;
        tailNode = temp; //move tailNode point to the last entry
        printf("Connecting to Tail Node done\n");
      else
        DeviceLinkList *temp = new DeviceLinkList;
        printf("Creating Head\n");
        temp = new DeviceLinkList;
        temp->deviceNumber = device;
        temp->nextNode = NULL;
        temp->prevNode = NULL;
        printf(".....DONE...!!!\n");
        headNode = temp;
        tailNode = headNode;
        printf("Finish Head-Tail Node creation\n");
      printf("Creation Done\n");
    }This is the one of function which export to JNI:
    JNIEXPORT void JNICALL Java_PBXdll_monitorStart  (JNIEnv * env, jobject obj, jstring callingdevice)
    char device[MAX_CstaDialingNumber];
    strcpy(device,env->GetStringUTFChars(callingdevice, 0));
    printf("Monitoring device: %s\n", device);
    startMonitor(device);
    deviceList -> addNode(device); // deviceList is the global variable
    }so...when i call the method monitorStart in java... it terminated abnormally with a Access Violation Exception.....the linked list can't be created.

  • Help with copying contents of file to link list please

    Hi,
    Below is a snippet of code I am playing with. As you can see I have created a LinkList, I now need to copy the contents of a csv file in to that list. The file is several lines long and I need each line in the list.
    I know how to add to the list manually i.e.,
    list.add("First entry in list");
    Could someone help me out with this please.
    Many thanks.
    (***CODE***)
    private LinkedList list = new LinkedList();
         public LinkTest()
              // ** List content START **
              // Open the file today.csv
              File inFile = new File("C:\\today.csv");
         // Create a file stream, wrapping the file
         FileReader fileReader = new FileReader(inFile);
         // Create a second wrapper,
    BufferedReader bufReader = new BufferedReader(fileReader);
         // Read in the first line...
         String s;
         s = bufReader.readLine();
         list.add(s);
         StringTokenizer st = new StringTokenizer(s);
         while (st.hasMoreTokens())
    System.out.println(st.nextToken());
         // ** List content END **
         

    I looked at your code and I thought, what's the question for, it's already adding lines to the list. And then I looked again and had the same thought. The third time I looked I noticed you didn't code the loop that read all the lines from the file. Silly me, I thought your question had something to do with linked lists.
    Anyway, to answer your real question, which is how do you read all the lines from a text file:while ((s = bufReader.readLine()) != null) {
      // do something with the String s here
      // such as adding it to a linked list
    }

  • How to implement multiple queues in one circular buffer?

    Spoiler (Highlight to read)
    Recently I have successfully shared data of 2D array among different vis in a project, using circular buffer.
    However, there is only one circular buffer allowed in one project for one data type.
    I want different vis, running and getting data from circular buffer in different speed, all getting data as a queue from circular buffer. Like the circular buffer's read continuous mode.
    The problem is that after a vi reads in continuous mode, the read data is deleted from the circular buffer. Then other vis can not use them any more and can not keep track where they should begin to read again.
    So if it is possible that there are multiple pointers or queues in circular buffer to keep track the progress of different vis, and data only update when it gets input from DAQ but not deleted when read?   

    LawrenceChong wrote:
    Spoiler (Highlight to read)
    Recently I have successfully shared data of 2D array among different vis in a project, using circular buffer.
    However, there is only one circular buffer allowed in one project for one data type.
    I want different vis, running and getting data from circular buffer in different speed, all getting data as a queue from circular buffer. Like the circular buffer's read continuous mode.
    The problem is that after a vi reads in continuous mode, the read data is deleted from the circular buffer. Then other vis can not use them any more and can not keep track where they should begin to read again.
    So if it is possible that there are multiple pointers or queues in circular buffer to keep track the progress of different vis, and data only update when it gets input from DAQ but not deleted when read?   
    THe last time I wrote a multi-subscriber cirular buffer was in LV 6. Since then I have found that polymorphic queues perform much better so I now use multiple queues. One queue for each subscriber of the data. The subscribers are then responsible for maintaining their own histories.
    So just use multiple queues.
    Ben
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction

  • How to implement the RemoveLast function in a link list? check my code plz

    Hi guys,
    How to delete the last element in a user defined linklist. I am using the following code to find the last element of the list. It works fine, but i don't know how to remove that element ...
    public Object getRear()
                   rear=front;
                   while (rear !=null)
                        if (rear.getNext()!=null)
                             rear=rear.getNext();
                        else
                             break; //rear Node found
                   if (rear !=null) //list is not empty
                        return rear.getData();
                        return null; //list is empty
         }

    Sorry, I missed out on returning the last element:
    public Object delRear() {
      // I assume front is an instance field pointing to the first element
      if(front != null) {  // list contains something
        Element  rear, pred;  // I assume you have some type like this
        // determine predecessor of last element
        rear = front;
        pred = null;
        while(rear.getNext() != null) {
          pred = rear;
          rear = rear.getNext();
        if(pred == null)  front = null;  // delete only element
        else  pred.setNext(null);  // delete last element
        return  rear; // return deleted element
      else  return  null;

  • Implementation of Linked List class

    I am trying to implement the Linked List class for one week, but I couldn't figure it out. If you know, please let me know.

    Here is an example of a linked list. Hope that will help.
    // define a node of a linked list
    public class Node
    public int data; // point to data
    public Node next; // pointer to next node or point to null if end of list
    // listTest1
    public class ListTest1
    public static void main(String[] args)
    Node list;
    list = new Node();
    list.data = 3;
    list.next = new Node();
    list.next.data = 7;
    list.next.next = new Node();
    list.next.next.data = 12;
    list.next.next.next = null;
    Node current = list;
    while (current != null) {
    System.out.print(current.data + " ");
    current = current.next;
    System.out.println();
    // other listnode
    public class ListNode
    public int data;
    public ListNode next;
    public ListNode()
    // post: constructs a node with data 0 and null link
    this(0, null);
    public ListNode(int value)
    // post: constructs a node with given data and null link
    this(value, null);
    public ListNode(int value, ListNode link)
    // post: constructs a node with given data and given link
    data = value;
    next = link;
    Contents of ListTest2.java
    public class ListTest2
    public static void main(String[] args)
    ListNode list = new ListNode(3, new ListNode(7, new ListNode(12)));
    ListNode current = list;
    while (current != null) {
    System.out.print(current.data + " ");
    current = current.next;
    System.out.println();

  • Faster way to search linked list?

    I'm pretty new to programming and I have to write a kind of psuedo implementation of a cache using a linked list (has to be a linked list). The problem is when I'm setting the maximum size of the linked list to a high number (like 2000), it goes incredibly slow. I don't know how I can make this faster.
    Here are the 2 main methods I'm using for it:
    public void addObject(Object toAdd){
         cacheList.addFirst(toAdd);
         if(cacheList.size()>=maxAllowedSize){
              removeObject(maxAllowedSize-1);
    public boolean containsObject(Object toFind){
         boolean test=false;
         for(int x=0;x<cacheList.size();x++){
              if(toFind.equals(cacheList.get(x))){
                   test=true;
                   hits++;
                   removeObject(x);
                   addObject(toFind);
                   x=cacheList.size(); //ends for loop
         total++;
         return test;
    }Where maxAllowedSize is a command line argument and removeObject just calls cacheList.remove(index).
    For testing, I'm using a text file with something over 1.3 million words and using scanner to read them. Here is the code that calls the two methods:
    if(!cache.containsObject(currentWord)){
         cache.addObject(currentWord);
    }Since containsObject adds the word itself, this calls addObject if the word isn't found (added to the front of the list).
    Any help is greatly appreciated.

    darkambivalence wrote:
    Linked list is what was specified in my assignment.
    Then to be honest I expect that part of the learning of assignment is to see how a LinkedList is a poor choice for a list that you want to search.
    Why will that run poorly? Because what do you think remove is doing? The remove has to search to find the thing you want to remove. So it's doing that search twice. So it will be twice as slow.
    There really isn't much you can do to make this faster. LinkedLists are great for many reasons but "random" accessing (for searching for example) is not one of them. I suppose if one really wanted to squeeze out performance you could keep the list sorted. So when inserting insert into the "right" place in the list and then as you search if a value would fall in between two buckets and doesn't exist in your list you can stop there. A doubly linked list would probably help for this implementation.
    In the real world though you would either not use a LinkedList at all or a Map depending on the needs.

  • Create a linked list

    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
    Maddy

    References 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

  • Problem with Queue and linked list

    Hi... i've got an assignment it start like this.
    You are required to write a complete console program in java includin main() to demonstrate the following:
    Data Structure: Queue, Priority Queue
    Object Involved: Linked-List, PrintJob
    Operations Involved:
    1. insert
    2. remove
    3. reset
    4. search
    Dats all... I've been given this much information... Can any1 try to help me please... How to make a start??? And wat does the print job means???
    Can any1 tell me wat am supposed to do...

    Hi,
    Why don't you start your demo like this?
    import java.io.IOException;
    public class Demo {
         public Demo() {
         public void startDemo() throws IOException {
              do {
                   System.out.println("String Console Demo ");
                   System.out.println("\t" + "1. Queue Demo");
                   System.out.println("\t" + "2. PriorityQueue Demo");
                   System.out.println("\t" + "3. LinkedList Demo");
                   System.out.println("\t" + "4. PrintJob Demo");
                   System.out.println("Please choose one option");
                   choice = (char) System.in.read();
                   showDemo(choice);
              } while (choice < '1' || choice > '4');
         public void showDemo(char ch) {
              switch (ch) {
              case '1':
                   System.out.println("You have chosen Queue Demo ");
                   showOperations();
                   break;
              case '2':
                   System.out.println("You have chosen Priority Queue Demo ");
                   showOperations();
                   break;
              case '3':
                   System.out.println("You have chosen LinkedList Demo ");
                   showOperations();
                   break;
              case '4':
                   System.out.println("You have chosen Print Job Demo ");
                   showOperations();
                   break;
         private void showOperations() {
              System.out.println("Please choose any operations ");
              System.out.println("\t" + "1. Insert ");
              System.out.println("\t" + "2. Remove ");
              System.out.println("\t" + "3. Reset ");
              System.out.println("\t" + "4. search ");
         public static void main(String[] args) throws IOException {
              Demo demo = new Demo();
              demo.startDemo();
         private char choice;
    Write a separate classes for the data structures show the initial elements and call the methods based on the operations then show the result.
    Thanks

Maybe you are looking for

  • Ipad 1 upgraded to iOS 5, "play where left off" video function no longer works, and codecs aren't recognized.

    for some reason after updating to iOS 5, my videos no longer play where i left off, even if i set on the settings to do so. and yes i've tried restoring again, playing video over and over. resetting the video over and over. after a while of tinkering

  • How do I set print size when printing from an IPhone or IPad?

    I have an HP Deskjet 3520. Today (11/24/12) is the first time I tried to e-print with both an IPhone and IPad (both IOS 6.01).  I was able to print easily from both devices. I tried a document from the Notes app on the IPhone and a photo from both th

  • How to find out download speed

    I've just upgraded my internet access and am curious as to what my current download speed is. There doesn't seem to be an easy way to find this out. Can anyone help? Is there something in the OS that would indicate this information? Is there a widget

  • Mobile connectivity to the internet

    There does not appear to be port fr data card in the 12" G4. How am I supposed to use the internet while on the move.

  • Can't export Pages document to PDF

    I have been trying to export a Pages document to PDF a number of times and get the following message: "The application Pages quit unexpectedly." I have rebooted and still can't export. Can anyone help, please? Thanks so much.