Wednesday, June 9, 2010

Queue in C++, without passing pointers

1: #include <stdio.h>
2: #include <iostream>
3: 
4: #define CAP 10
5: //in case of c++, if there is no need to pass the pointers
6: //of head and tail as they are members of the class itself
7: //and the member functions can access them and modify them
8: class queue
9: {
10:   typedef struct node
11:   {
12:     struct node *next;
13:     int data;
14:   }qNode;
15:   
16:   qNode *head;
17:   qNode *end;
18:   int cap;
19:   int size;
20: public:
21:   queue(int cap = CAP);
22:   int dequeue();
23:   int enqueue(int data);
24:   void show();
25: };
26: 

27: //make a queue with default capacity
28: //and default value
29: queue::queue(int cap):head(NULL),end(NULL),cap(CAP),size(0)
30: {
31:   int i = 0;
32:   while(size < cap)
33:     enqueue(i++);
34: }
35: 
36: //queue will shorten from head
37: int queue::dequeue()
38: {
39:   if(head == NULL)
40:     return 0;
41:   
42:   qNode *temp = head;
43:   int data = head->data;
44:   head = head->next;
45:   return data;
46: }
47: 
48: //queue will grow from tail
49: int queue::enqueue(int data)
50: {
51:   if(size == cap)
52:     return 0;
53:   
54:   qNode *newNode = new qNode;
55:   if(newNode == NULL)
56:     return 0;
57:     
58:   newNode->data = data;
59:   newNode->next = NULL;
60:   
61:   if(end == NULL)//first node
62:   {
63:     head = newNode;
64:     end = newNode;
65:     size++;
66:   }
67:   else
68:   {
69:     end->next = newNode;
70:     end = newNode;
71:     size++;
72:   }
73:   std::cout<<"size is "<<size<<"cap is "<<cap<<std::endl; 
74: }
75: 
76: void queue::show()
77: {
78:   int d = dequeue();
79:   std::cout<<"top is "<<d<<std::endl;
80:   //return -1;
81: }
82: 
83: int main(int argc, char **argv)
84: {
85:   queue myQueue;
86:   myQueue.show();
87:   myQueue.show();
88:   myQueue.show();
89:   myQueue.show();
90:   myQueue.show();
91:   myQueue.show();
92:   myQueue.show();
93:   myQueue.show();
94:   myQueue.show();
95:   myQueue.show();
96:   myQueue.show();
97:   myQueue.show();
98: 
99:   printf("hello world\n");
100:   return 0;
101: }
102: 

No comments: