enqueue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class ready_queue{
	private:
	ready_queue *temp, *temp2;
	ready_queue *start_ptr;
	ready_queue *current;
	ready_queue *nxt;
	int pid;
	public:
        void enqueue();
};

ready_queue::ready_queue()
{
		start_ptr = NULL;
}

 void ready_queue::enqueue() {
     temp = new ready_queue;
	 cin >> temp -> pid;
	 temp->nxt = NULL;
     
     if (start_ptr == NULL){ 
	       start_ptr = temp;
	       current = start_ptr;
       }
     else{ 
	       temp2 = start_ptr;
     while (temp2->nxt != NULL){  
	       temp2 = temp2->nxt;
       }
      temp2->nxt = temp;
   }
}



This enqueue function works fine, but I don't want to enter the value of the queue's, I want the queue to start from 1 and proceed, how to do this?


EDIT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class ready_queue{
	private:
	   ready_queue *temp, *temp2;
	   ready_queue *start_ptr;
	   ready_queue *current;
	   ready_queue *nxt;
	   int name;
	public:
          void enqueue();
};

ready_queue::ready_queue()
{
		start_ptr = NULL;
               name = 1;
}

 void ready_queue::enqueue() {
     temp = new ready_queue;
	 temp -> name;
	 temp->nxt = NULL;
     
     if (start_ptr == NULL){ 
	       start_ptr = temp;
	       current = start_ptr;
       }
     else{ 
	       temp2 = start_ptr;
     while (temp2->nxt != NULL){  
	       temp2 = temp2->nxt;
       }
      temp2->nxt = temp;
   }
}


If I do this, it just enqueues 1 into the queue every time, but I need it to increment.
Last edited on
Pass the value that you wish to enqueue as a parameter:
void ready_queue::enqueue(int val)

A few other suggestions:
temp and temp2 should be local variables inside read_queue::enqueue(), not members of the ready_queue class. This is because they aren't needed outside enqueue().

Consider what happens if you put 100 items in the queue. You end up with 100 ready_queue instances, each with a start_ptr, current, nxt and name. In reality, you only need one start_ptr for the queue, and one current_ptr. But you still need a nxt ptr for each item on the queue. What to do?

The answer is to create two classes: ready_queue and ready_queue_item:
1
2
3
4
5
6
7
8
9
10
11
12
13
class ready_queue_item {
public:
	   ready_queue_item *nxt;
	   int name;
};

class ready_queue{
	private:
	   ready_queue_item *start_ptr;
	   ready_queue_item *current;
	public:
          void enqueue(int val);
};

Define constructors for both of these, that way it's impossible to mess up and create them with garbage values.
Topic archived. No new replies allowed.