[ create a new paste ] login | about

Link: http://codepad.org/IHwWk2zZ    [ raw code | output | fork | 2 comments ]

AaronMiller - C++, pasted on Sep 11:
/*
 * Queue Class
 * Written by Aaron J. Miller (20110911)
 */
#include <cstdio>
#include <cassert>

//==============================================================================
// Queue Class
//==============================================================================
template<typename T> class CQueue {
protected:
	struct item_s {
		T obj;
		struct item_s *next;
	} *m_head, *m_tail;

public:
	inline CQueue(): m_head((item_s *)0), m_tail((item_s *)0) {
	}
	inline ~CQueue() {
		while(!IsEmpty())
			Pop();
	}

	inline bool IsEmpty() {
		return m_head!=(item_s *)0?false:true;
	}
	inline void Push(const T &obj) {
		item_s *p;

		p = new item_s();
		p->obj = obj;
		p->next = (struct item_s *)0;

		if (m_tail)
			m_tail->next = p;
		else
			m_head = p;
		m_tail = p;
	}
	inline T Pop() {
		item_s *next;
		T obj;

		assert(!IsEmpty());

		next = m_head->next;

		obj = m_head->obj;
		delete m_head;

		if (!(m_head = next))
			m_tail = (item_s *)0;

		return obj;
	}
};

//==============================================================================
// Test Code
//==============================================================================
int main() {
  CQueue<int> int_queue;

  int_queue.Push(42);
  int_queue.Push(23);
  int_queue.Push(17);
  int_queue.Push(47);
  int_queue.Push(1);
  int_queue.Push(2);
  int_queue.Push(3);

  while(!int_queue.IsEmpty())
    printf("%d\n", int_queue.Pop());

  return 0;
}


Output:
1
2
3
4
5
6
7
42
23
17
47
1
2
3


Create a new paste based on this one


Comments:
posted by AaronMiller on Sep 11
Huh, it worked on the first attempt. It's always awesome when that happens. Anyway, the above isn't meant to be efficient, just wanted to test it before trying to compile it into the whole project. (Though, to be fair, this probably took more time than it would've than to just test within the project.)

NOTE: It really isn't meant to be efficient, and a lot can be done to make this more efficient.
reply
posted by AaronMiller on Sep 11
reply