今天我们继续聊聊栈(Stack)
栈:
栈是一种线性存储结构,它有以下几个特点:
(01) 栈中数据是按照"后进先出(LIFO, Last In First Out)"方式进出栈的。
(02) 向栈中添加/删除数据时,只能从栈顶进行操作。
其实在现实生活中,有很直观的例子。比如,你把几本书从下往上叠,如果想要拿出书,肯定是先把上面的书拿开,才可以拿到下面的书。而越是放在上面的书,都是越往后才放上去的书。
栈通常使用的操作:push、peek、pop、isEmpty。
push -- 向栈中添加元素。(添加到栈顶)
peek -- 返回栈顶元素。
pop -- 返回并删除栈顶元素的操作
isEmpty -- 如果栈是空的话,返回 true
python 实现:
def createStack():
stack = []
return stack
def isEmpty(stack):
return len(stack) == 0
def push(stack, item):
stack.append(item)
print("pushed to stack " + item)
def peek(stack):
if (isEmpty(stack)):
return false
return stack[len(stack)-1]
def pop(stack):
if (isEmpty(stack)):
return false
return stack.pop()
stack = createStack()
push(stack, str(10))
push(stack, str(20))
push(stack, str(30))
print(pop(stack) + " popped from stack")
测试代码:
10 pushed to stack
20 pushed to stack
30 pushed to stack
30 popped from stack
c 语言代码实现:数组实现的栈,并且只能存储Int数据(代码链接)
#include <stdio.h>
#include <malloc.h>
/**
* C 语言: 数组实现的栈,只能存储int数据。
*
* @author skywang
* @date 2013/11/07
*/
// 保存数据的数组
static int *arr=NULL;
// 栈的实际大小
static int count;
// 创建“栈”,默认大小是12
int create_array_stack(int sz)
{
arr = (int *)malloc(sz*sizeof(int));
if (!arr)
{
printf("arr malloc error!");
return -1;
}
return 0;
}
// 销毁“栈”
int destroy_array_stack()
{
if (arr)
{
free(arr);
arr = NULL;
}
return 0;
}
// 将val添加到栈中
void push(int val)
{
arr[count++] = val;
}
// 返回“栈顶元素值”
int peek()
{
return arr[count-1];
}
// 返回“栈顶元素值”,并删除“栈顶元素”
int pop()
{
int ret = arr[count-1];
count--;
return ret;
}
// 返回“栈”的大小
int size()
{
return count;
}
// 返回“栈”是否为空
int is_empty()
{
return size()==0;
}
// 打印“栈”
void print_array_stack()
{
if (is_empty())
{
printf("stack is Empty\n");
return ;
}
printf("stack size()=%d\n", size());
int i=size()-1;
while (i>=0)
{
printf("%d\n", arr[i]);
i--;
}
}
void main()
{
int tmp=0;
// 创建“栈”
create_array_stack(12);
// 将10, 20, 30 依次推入栈中
push(10);
push(20);
push(30);
//print_array_stack(); // 打印栈
// 将“栈顶元素”赋值给tmp,并删除“栈顶元素”
tmp = pop();
printf("tmp=%d\n", tmp);
//print_array_stack(); // 打印栈
// 只将“栈顶”赋值给tmp,不删除该元素.
tmp = peek();
printf("tmp=%d\n", tmp);
//print_array_stack(); // 打印栈
push(40);
print_array_stack(); // 打印栈
// 销毁栈
destroy_array_stack();
}
参考链接:
(1)http://www.geeksforgeeks.org/stack-data-structure-introduction-program/
题目:面试题7-用两个栈实现队列(剑指offer)
题目描述:
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
解题思路:
栈:后进先出(LIFO);
队列:先进先出(FIFO).
入队:将元素进栈A
出队:判断栈B是否为空,如果为空,则将栈A中所有元素pop,并push进栈B,栈B出栈;
如果不为空,栈B直接出栈
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.stack1 = []
self.stack2 = []
def push(self, node):
# write code here
self.stack1.append(node)
def pop(self):
# return xx
if self.stack2 == []:
while self.stack1:
self.stack2.append(self.stack1.pop())
return self.stack2.pop()