栈——C语言实现、python实现

本文详细介绍了栈这种数据结构,包括其基本概念、后进先出(LIFO)的特点、以及常用的压栈(push)、出栈(pop)和读取栈顶元素(top)等操作。通过C语言和Python的具体实现示例,帮助读者深入理解栈的工作原理。

栈是一种限制其插入和删除均只能在一个位置上进行的表,通常该位置被称为栈顶;其示意图如下:


根据其结构可知其中的数据有后进先出的规律,故栈又被叫做LIFO(last in first out);

对栈的常用操作主要有:
压栈操作(push):将元素从栈顶插入,并更新栈顶位置
出栈操作(pop):将栈顶的元素删除,并更新栈顶位置
读取栈顶元素(top):读取栈顶的元素

栈也是一种表,所以所有实现表的方法均能用来实现栈; 下面采用数组实现方式:


C语言实现:

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

typedef struct stack_type stack_t;
struct stack_type {
	int capacity;/*栈的容量*/
	int top;    /*栈顶元素下标*/
	int *array;
};

stack_t *create_stack(int capacity);
void destroy_stack(stack_t *stk);
int is_empty(stack_t *stk);
int is_full(stack_t *stk);
void push(stack_t *stk, int element);
void pop(stack_t *stk);
int top(stack_t *stk);

int main(int argc, char *argv[])
{
	stack_t *stk = NULL;

	int capacity;
	printf("input capacity:");
	scanf("%d", &capacity);
	stk = create_stack(capacity);
	printf("op:\n\
	1 for push\n\
	2 for top\n\
	3 for pop\n\
	0 for quit\n");

	int i = 1;
	int element;
	while (i != 0) {
		scanf("%d", &i);
		switch (i) {
			case 1:
				printf("insert element: ");
				scanf("%d", &element);
				push(stk, element);
				break;
			case 2:
				if (!is_empty(stk))
					printf("top: %d\n", top(stk));
				else
					printf("stack is empty.\n");
				break;
			case 3:
				printf("pop\n");
				pop(stk);
				break;
			case 4:
				printf("destroy queue.\n");
				destroy_stack(stk);
				i = 0;
				break;
			default:
				break;
		}
	}

	return 0;
}

stack_t *create_stack(int capacity)
{
	if (capacity < 1)
		return NULL;

	stack_t *stk = (stack_t *)malloc(sizeof(stack_t));
	assert(stk != NULL);
	stk->capacity = capacity;
	stk->top = -1;
	stk->array = (int *)malloc(sizeof(int) * capacity);
	assert(stk->array != NULL);

	return stk;
}

void destroy_stack(stack_t *stk)
{
	if (NULL == stk)
		return;
	free(stk->array);
	free(stk);
}

int is_empty(stack_t *stk)
{
	return (-1 == stk->top);
}

int is_full(stack_t *stk)
{
	return (stk->top == stk->capacity-1);
}

void push(stack_t *stk, int element)
{
	if (NULL == stk)
		return;
	if (is_full(stk)) {
		printf("stack is full\n");
		return;
	}

	stk->array[++stk->top] = element;
}

void pop(stack_t *stk)
{
	if (NULL == stk)
		return;
	if (is_empty(stk)) {
		printf("stack is empty\n");
		return;
	}

	--stk->top;
}

int top(stack_t *stk)
{
	return stk->array[stk->top];
}


python中的list类型可以很方便的实现实现栈,下面一种直接定义栈,另一种继承list实现栈:

class stack:
    def __init__(self):
        self.mstk = []

    def is_empty(self):
        return 0 == len(self.mstk)

    def push(self, element):
        self.mstk.append(element)

    def top(self):
        try:
            if self.is_empty():
                raise Exception
            return self.mstk[-1]
        except Exception:
            print 'top(): stack is empty'
        
    def pop(self):
        try:
            self.mstk.pop()
        except Exception:
            print 'pop(): stack is empty'

    def size(self):
        return len(self.mstk)

def main():
    mstk = stack()
    for i in range(1, 11):
        mstk.push(i)

    while not mstk.is_empty():
        print mstk.top(),
        mstk.pop()
    print 
    mstk.pop()
    mstk.top()
    print 'size: ', mstk.size()

if __name__ == '__main__':
    main()


;;;

class stack(list):
    def __init__(self):
        super(stack, self).__init__()

    def size(self):
        return len(self)
    
    def is_empty(self):
        return 0 == len(self)

    def push(self, element):
        self.append(element)

    def top(self):
        try:
            return self[-1]
        except IndexError:
            print 'top(): stack is empty'
            
    def pop(self):
        try:
            super(stack, self).pop()
        except IndexError:
            print 'pop(): stack is empty'

def main():
    mstk = stack()
    for i in range(1, 11):
        mstk.push(i)

    while not mstk.is_empty():
        print mstk.top(),
        mstk.pop()
    print 
    mstk.top()
    mstk.pop()
    print 'size', mstk.size()
    
if __name__ == '__main__':
    main()



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值