队列 FIFO

#include <iostream>
using namespace std;

typedef double T;

class List{
	struct Node{
		T data;
		Node* next;
		Node(const T& t=T()):data(t)
		{
			next = NULL;
		}
	};
	Node* head;
public:
	List():head(NULL)
	{
		
	}
	void clear()
	{
		while(head != NULL)
		{
			Node* q = head->next;
			delete head;
			head = q;
		}
	}
	~List()
	{
		clear();
	}
	void insert_front(const T& t)
	{
		Node* p = new Node(t);
		p->next= head;
		head = p;
	}
	
	void insert_back(const T& t)
	{
		Node* p = new Node(t);
		if (head==NULL)
			head = p;
		else
		{
			get_pointer(size()-1)->next = p;
		}
	}
	
	void travel()
	{
		Node* p=head;
		while(p != NULL)
		{
			cout << p->data << ' ';
			p = p->next; 
		}
		cout << endl;
	}
	int size()
	{
		int cnt = 0;
		Node* p = head;
		while(p != NULL)
		{
			cnt++;
			p = p->next;
		}
		return cnt;
	}
	
	T get_head()
	{
		if (head == NULL)
		{
			throw "no head";
		}	
		return head->data;
	}
	T get_tail()
	{
		if (head == NULL)
			throw "no tail";
		Node* p = head;
		while(p->next != NULL)
		{
			p = p->next;
		}
		return p->data;
	}
	
	bool empty()
	{
		return head == NULL;
	}
	
	int find(const T& t)
	{
		int pos = 0;
		Node* p = head;
		while(p != NULL)
		{
			if (p->data== t)
				return pos;
			p = p->next;
			pos++;
		}
		return -1;
	}
	bool update(const T& o, const T& n)
	{
		int pos = find(o);
		if (pos == -1)
			return false;
		Node* p = get_pointer(pos);
		p->data = n;
		
		return true;
	}
private:
	Node* get_pointer(int pos)
	{
		Node* p = head;
		for (int i=0; i<pos; i++)
			p = p->next;
		
		return p;
	}
public:
	bool erase(const T& t)
	{
		int pos = find(t);
		if (pos == -1)
			return false;
		if (pos ==0)
		{
			Node* q = head->next;
			delete head;
			head = q;
		}
		else
		{
			Node* pre = get_pointer(pos-1);
			Node *cur = pre->next;
			pre->next= cur->next;
			delete cur;
		}
	}	
};

class Queue{
	List l;
public:
	void push(const T& t)  //数据入队列 
	{
		l.insert_back(t);	
	}
	void pop()  //删除队首元素 
	{
		l.erase(l.get_head());
	}
	T front()  //取得队列首元素
	{
		return l.get_head();	
	} 
	T back()	//取得队列尾元素
	{
		return l.get_tail();	
	} 
	bool empty()  //判断队列是否为空 
	{
		return l.empty();
	} 
	int size()	//取得队列中的元素个数
	{
		return l.size();	
	} 
	void clear()	//清空整个队列
	{
		l.clear();
	} 
};

int main()
{
	Queue q;
	q.push(1.0);
	q.push(2.0);
	q.push(3.0);
	q.push(4.0);
	q.push(5.5);
	cout.setf(ios::showpoint);  //格式化输出,带小数部分 
	while(!q.empty())
	{
		cout << q.front() << ' ';
		q.pop();
	}
	cout << endl;
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值