473,662 Members | 2,406 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Undefined use of next in a queue?

16 New Member
I was looking over an example queue and was confused about the way it works.


it creates a node called next, but never really does anything with it. Later in the queue it refers to it the way
you would expect next to work. But since we never did anything with next, it makes no sense that it would act
the way its used. Its just a random node. Why is it possible to use it in a distinctive way?


Expand|Select|Wrap|Line Numbers
  1.  // Queue.java
  2. // An integer queue ADT
  3.  
  4. class Queue{
  5.  
  6.    private class Node{
  7.       // Fields
  8.       int data;
  9.       Node next;
  10.       // Constructor
  11.       Node(int data) { this.data = data; next = null; }
  12.       // toString:  Overides Object's toString method.
  13.       public String toString() { return String.valueOf(data); }
  14.    }
  15.  
  16.    // Fields
  17.    private Node front;
  18.    private Node back;
  19.    private int length;
  20.  
  21.    // Constructor
  22.    Queue() { front = back = null; length = 0; }
  23.  
  24.  
  25.    // Access Functions //////////////////////////////////////////////////////////////////
  26.  
  27.    // getFront(): returns front element in this queue
  28.    // Pre: !this.isEmpty()
  29.    int getFront(){
  30.       if( this.isEmpty() ){
  31.          throw new RuntimeException("Queue Error: getFront() called on empty Queue");
  32.       }
  33.       return front.data;
  34.    }
  35.  
  36.    // getLength(): returns length of this queue
  37.    int getLength() { return length; }
  38.  
  39.    // isEmpty(): returns true if this is an empty queue, false otherwise
  40.    boolean isEmpty() { return length==0; }
  41.  
  42.  
  43.    // Manipulation Procedures ///////////////////////////////////////////////////////////
  44.  
  45.    // Enqueue(): appends data to back of this queue
  46.    void Enqueue(int data){
  47.       Node node = new Node(data);
  48.       if( this.isEmpty() ) { front = back = node; }
  49.       else { back.next = node; back = node; }
  50.       length++;
  51.    }
  52.  
  53.    // Dequeue(): deletes element from front of this queue
  54.    // Pre: !this.isEmpty()
  55.    void Dequeue(){
  56.       if(this.isEmpty()){
  57.          throw new RuntimeException("Queue Error: Dequeue() called on empty Queue");
  58.       }
  59.       if(this.length>1) {front = front.next;}
  60.       else {front = back = null;}
  61.       length--;
  62.    }
  63.  
  64.  
  65.    // Other Functions ///////////////////////////////////////////////////////////////////
  66.  
  67.    // toString():  overides Object's toString() method.
  68.    public String toString(){
  69.       String str = "";
  70.       for(Node N=front; N!=null; N=N.next){
  71.          str += N.toString() + " ";
  72.       }
  73.       return str;
  74.    }
  75.  
  76.    // equals(): returns true if this Queue is identical to  Q, false otherwise.
  77.    boolean equals(Queue Q){
  78.       boolean flag  = true;
  79.       Node N = this.front;
  80.       Node M = Q.front;
  81.  
  82.       if( this.length==Q.length ){
  83.          while( flag && N!=null){
  84.             flag = (N.data==M.data);
  85.             N = N.next;
  86.             M = M.next;
  87.          }
  88.          return flag;
  89.       }else{
  90.          return false;
  91.       }
  92.    }
  93.  
  94.    // copy(): returns a new Queue identical to this one.
  95.    Queue copy(){
  96.       Queue Q = new Queue();
  97.       Node N = this.front;
  98.  
  99.       while( N!=null ){
  100.          Q.Enqueue(N.data);
  101.          N = N.next;
  102.       }
  103.       return Q;
  104.    }
  105.  
  106. }
  107.  
Jun 27 '11 #1
1 1610
Nepomuk
3,112 Recognized Expert Specialist
OK, let's have a look at every place that next is used:
Expand|Select|Wrap|Line Numbers
  1. Node next;
  2. //...
  3. Node(int data) { this.data = data; next = null; }
A so far empty node called next is defined. Also, in the constructor it is initialized as null. Pretty simple so far.
Expand|Select|Wrap|Line Numbers
  1. // Enqueue(): appends data to back of this queue
  2. void Enqueue(int data){
  3.    Node node = new Node(data);
  4.    if( this.isEmpty() ) { front = back = node; }
  5.    else { back.next = node; back = node; }
  6.    length++;
  7. }
OK, here it get's interesting. If the current node isn't empty, next is defined as the new Node node so now it exists as a real (so far empty) object.
Expand|Select|Wrap|Line Numbers
  1. // Dequeue(): deletes element from front of this queue
  2. // Pre: !this.isEmpty()
  3. void Dequeue(){
  4.    if(this.isEmpty()){
  5.       throw new RuntimeException("Queue Error: Dequeue() called on empty Queue");
  6.    }
  7.    if(this.length>1) {front = front.next;}
  8.    else {front = back = null;}
  9.    length--;
  10. }
If the queue is longer than 1 item, the node front is defined as front.next, so effectively front (the first element of the queue) is removed from the queue.

OK, now it's also used in toString(), equals() and copy(), but as they just read it those aren't important here.

So, to summarize: in every node we have a reference to the first, last and next element, which we define while building up the queue. Does that answer your question?

Greetings,
Nepomuk
Jun 28 '11 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

4
2770
by: Sachin Jagtap | last post by:
Hi, I am getting exception while poping item from queue, I am writing messages coming from client in a queue in one thread and then in other thread i am reading from queue and writing in file. I have not implemented any syncronization between reading and wrinting, just i checking size of queue, if it is not empty i am reading from queue and wrting to file. somethign like
14
2961
by: Gregory L. Hansen | last post by:
I can't seem to make a queue of objects, using the STL queue. I'm trying to make a little event manager, and I just want someplace to store events. The method definitions for EventManager have been commented away to nothing during debugging, but the headers look like class Event { private: Object* recipient; int eventID;
6
37420
by: herrcho | last post by:
#include <stdio.h> #define MAX 10 int queue; int front, rear; void init_queue() { front=rear=0; }
16
6894
by: William Stacey [MVP] | last post by:
Anyone care to comment on if this non-blocking queue implementation is sound? /// <summary> /// Summary description for NonBlockingQueue. /// Modeled after: http://www.cs.rochester.edu/u/scott/synchronization/pseudocode/queues.html /// </summary> public class NonBlockingQueue {
3
5147
by: Kceiw | last post by:
Dear all, When I use #include "queue.h", I can't link it. The error message follows: Linking... G:\Projects\Datastructure\Queue\Debug\main.o(.text+0x136): In function `main': G:\Projects\Datastructure\Queue\main.cpp:16: undefined reference to `Queue<char>::Queue()' G:\Projects\Datastructure\Queue\Debug\main.o(.text+0x394): In function `Z10do_commandcR5QueueIcE':
4
10274
by: Russell Warren | last post by:
I'm guessing no, since it skips down through any Lock semantics, but I'm wondering what the best way to clear a Queue is then. Esentially I want to do a "get all" and ignore what pops out, but I don't want to loop through a .get until empty because that could potentially end up racing another thread that is more-or-less blindly filling it asynchronously. Worst case I think I can just borrow the locking logic from Queue.get and clear...
2
2927
by: ecestd | last post by:
how do you implement a copy constructor for this pointer-based ADT queue #include <cassert // for assert #include <new // for bad_alloc using namespace std; //private:{Queue::Queue(const Queue& Q)}
0
2735
by: ecestd | last post by:
I did implement the copy constructor but still have a problem with it. It is not working. What could be wrong? #include "QueueP.h" #include <cassert // for assert #include <new // for bad_alloc #include <iostream> //typedef std::queue<QueueItemTypeQueue; using namespace std; //private:{Queue::Queue(const Queue& Q)}
4
8400
hemantbasva
by: hemantbasva | last post by:
We have designed an aspx page having five ajax tab in it. the data of first four are designed on page whereas for the fifth tab it renders a user control named MYDOMAIN. in the tab container's even onactivetabindexchanged we have called a method loadtabpanel() which is defined in javascript in same page.the problem is it sometime give the message load tab panel undefined. this error does not come regularly. it comes in usercontrol rendering . i...
14
16953
by: AlarV | last post by:
Hello everyone, here is my problem. I have to make a dynamic priority queue,which is a heap, and my book isn't helpful at all, so I have no clues on how to create it.. I read something like a static priority queue, which is an array heap, and for example i/2 is the father of i and so on.. the code of the static priority queue is this: int i= ++CurrentSize; while(i != 1 && X > heap) { // cannot put x in heap heap = heap; //move...
0
8432
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8343
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
8545
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7365
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6185
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5653
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4347
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2762
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1747
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.