STL学习之stack

栈(statck)这种数据结构在计算机中是相当出名的。栈中的数据是先进后出的(First In Last Out, FILO)。栈只有一个出口,允许新增元素(只能在栈顶上增加)、移出元素(只能移出栈顶元素)、取得栈顶元素等操作。在STL中,栈是以别的容器作为底部结构,再将接口改变,使之符合栈的特性就可以了。因此实现非常的方便。下面就给出栈的函数列表和VS2008中栈的源代码,在STL中栈一共就5个常用操作函数(top()、push()、pop()、 size()、empty() ),很好记的。



 

 

 



 

可以看出,由于栈只是进一步封装别的数据结构,并提供自己的接口,所以代码非常简洁,如果不指定容器,默认是用deque来作为其底层数据结构的(对deque不是很了解?可以参阅《STL系列之一 deque双向队列》)。下面给出栈的使用范例:

//栈 stack支持 empty() size() top() push() pop()
// by MoreWindows(http://blog.csdn.net/MoreWindows)
#include <stack>
#include <vector>
#include <list>
#include <cstdio>
using namespace std;
int main()
{
	//可以使用list或vector作为栈的容器,默认是使用deque的。
	stack<int, list<int>>      a;
	stack<int, vector<int>>   b;
	int i;
	
	//压入数据
	for (i = 0; i < 10; i++)
	{
		a.push(i);
		b.push(i);
	}

	//栈的大小
	printf("%d %d\n", a.size(), b.size());

	//取栈项数据并将数据弹出栈
	while (!a.empty())
	{
		printf("%d ", a.top());
		a.pop();
	}
	putchar('\n');

	while (!b.empty())
	{
		printf("%d ", b.top());
		b.pop();
	}
	putchar('\n');
	return 0;
}

 

关于stack在面试中的运用可以有以下题目:

题目:输入一个链表的头结点,从尾到头反过来输出每个结点的值。链表结点定义如下:

struct ListNode

{

    int       m_nKey;

    ListNode* m_pNext;

 

};

 

代码如下:

#include <iostream>
using namespace std;

struct node
{
	int data;
	node *next

};

void ptintlist(node *head)
{
	stack<node *> nodes;
	node *p=head;
	while (p!=NULL)
	{
		nodes.push(p);
		p=p->next;
	}
	while (!nodes.empty())
	{
		p=nodes.top();
		cout<<p->data;
		nodes.pop();
	}
}

 以上内容转之“http://blog.csdn.net/morewindows/article/details/6950881

另外一种关于递归的解法如下:

void PrintListReversely(ListNode* pListHead)
{
	if(pListHead != NULL)
	{
		// Print the next node first
		if (pListHead->m_pNext != NULL)
		{
			PrintListReversely(pListHead->m_pNext);
		}
 
		// Print this node
		printf("%d", pListHead->m_nKey);
	}
}

 

 

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值