栈实现队列,链表实现栈




栈实现队列:

#include
#include

templateclass Queue
{
	std::stack st1, st2;
public:
	void enqueue(T head)
	{
		st1.push(head);
	}
	T pop()
	{
		while (!st1.empty())
		{
			st2.push(st1.top());
			st1.pop();
		}
		T tail = st2.top();
		st2.pop();
		while (!st2.empty())
		{
			st1.push(st2.top());
			st2.pop();
		}
		return tail;
	}
};

int main()
{
	Queue qint;
	for (int i = 1; i < 10; i++)
	{
		qint.enqueue(i);
	}
	std::cout << qint.pop() << std::endl;
	system("pause");

	return 0;
}





链表实现栈:

#include
#include

templateclass Stake
{
	std::list tempList;

public:
	void push(T e)
	{
		tempList.push_front(e);
	}

	T pop()
	{
		T tempEl = tempList.front();
		tempList.pop_front();
		return tempEl;
	}

	int length()
	{
		int num(0);
		std::list lList;
		while (!tempList.empty())
		{
			num++;
			lList.push_front(tempList.front());
			tempList.pop_front();
		}
		while (!lList.empty())
		{
			tempList.push_front(lList.front());
			lList.pop_front();
		}
		return num;
	}
};


int main()
{
	Stake testSt;

	for (int i = 0; i < 10; i++)
	{
		testSt.push(i);
	}

	//std::cout << testSt.length() << std::endl;

	for (size_t i = 0; i < testSt.length();)
	{
		std::cout << testSt.pop() << std::endl;
	}

	system("pause");

	return 0;
}


你可能感兴趣的:(C/C++)