一、栈的介绍

  栈作为一种数据结构,是一种只能在一端进行插入和删除操作。它按照先进后出的原则存储数据,先进入的数据被压入栈底,最后的数据在栈顶,需要读数据的时候从栈顶开始弹出数据(最后一个数据被第一个读出来)。栈被使用于非常多的地方,例如浏览器中的后退按钮,文本编辑器中的撤销机制。

进栈的时候是1先进,然后是2、3、4、5、6,出栈的时候是先6出,然后是5、4、3、2、1

二、栈中常用的方法

作为一个栈(用stack来表示),最基本的方法有下面几个:

  • stack.push(e): 将元素e添加到S的栈顶

  • stack.pop(): 从栈S中移除并返回栈顶的元素,如果此时栈是空的,那么这个操作将会报错

  • stack.top(): 不移除栈顶元素,但返回栈顶元素,如果此时栈是空的,那么这个操作将会报错

  • stack.is_empty(): 如果栈为空,则返回True,否则返回False

  • len(stack): 返回栈中元素的数量,使用len的特殊方法实现

  • stack.travel()遍历栈里面的元素

三、栈的python代码实现

class Stack():
"""
以list为基础实现的栈
""" def __init__(self):
self._data = [] def __len__(self):
return len(self._data) def is_empty(self):
if len(self._data) == 0:
return True
else:
return False def push(self, e):
self._data.append(e) def pop(self):
if self.is_empty():
print("栈为空")
return
return self._data.pop() def top(self):
if self.is_empty():
print("栈为空")
return
return self._data[-1] def travel(self):
for i in range(0,len(self._data)):
print("%d"%self._data[i]) if __name__ == '__main__':
print("创建栈")
stack = Stack()
stack.pop()
print("验证是否为空:",end="")
empty = stack.is_empty()
if empty == True:
print("空栈")
else:
print("不是空")
print("进栈")
stack.push(1)
stack.push(2)
stack.push(3)
stack.push(4)
stack.push(5)
stack.push(6)
print("遍历验证进栈")
stack.travel()
print("判断是否为空:",end=" ")
empty = stack.is_empty()
if empty == True:
print("空栈")
else:
print("不是空")
print("出栈:",end=" ")
pop = stack.pop()
print(pop)
stack.travel()
print("验证栈顶元素:",end=" ")
top = stack.top()
print(top)

运行结果为:

创建栈 栈为空 验证是否为空:空栈 进栈 遍历验证进栈 1 2 3 4 5 6 判断是否为空: 不是空 出栈: 6 1 2 3 4 5 验证栈顶元素: 5

四、栈的C语言代码实现

//  main.m
// 栈
// Created by 侯垒 on 2019/7/3.
// Copyright © 2019 可爱的侯老师. All rights reserved. # include<stdio.h> typedef struct N
{
int num;
struct N *next;
}Node; Node * createNode(int num)
{ Node *node = (Node *)malloc(sizeof(Node));
node->num = num;
node->next = NULL;
return node;
} Node * createStack()
{
Node *head = NULL;
return head;
} int is_empty(Node *head)
{
if (head == NULL)
{
return ;
}
else
{
return ;
} } int length(Node *head)
{
Node *current = head;
if (is_empty(head))
{
return ;
}
int count = ;
while (current->next!=NULL)
{
count++;
current = current->next;
}
return count;
} Node *push(Node *head, int num)
{
Node *node = createNode(num);
if (is_empty(head)==)
{
head = node;
}
else
{
Node *current = head;
while (current->next!=NULL)
{
current = current->next;
}
current->next = node;
}
return head;
} Node *pop(Node *head)
{
if (is_empty(head) == )
{
printf("站为空");
return head;
}
else
{
Node *current = head;
int len = length(head);
if (len == )
{
head = NULL;
}
else
{
for (int i=; i<len-;i++)
{
current = current->next;
}
current->next = NULL;
} }
return head;
} int top(Node *head)
{
if (is_empty(head))
{
printf("栈为空");
return -;
}
return head->num;
} void travel(Node *head)
{
if (is_empty(head) == )
{
printf("站为空\n");
}
else
{
Node *current = head;
int len = length(head);
for (int i = ; i<len; i++)
{
printf("%d ",current->num);
current = current->next;
}
printf("\n");
}
} int main(int argc, const char * argv[]) { printf("创建栈\n");
Node *head = createStack();
printf("验证是否为空: ");
int empty = is_empty(head);
if (empty == )
{
printf("栈为空\n");
}
else
{
printf("栈不为空\n"); }
printf("验证进栈\n");
head = push(head, );
travel(head);
head = push(head, );
head = push(head, );
head = push(head, );
head = push(head, );
head = push(head, );
travel(head);
printf("验证栈顶元素\n");
int t = top(head);
printf("top = %d\n",t); printf("验证出栈\n");
head = pop(head);
travel(head);
head = pop(head);
travel(head);
head = pop(head);
travel(head);
head = pop(head);
travel(head);
head = pop(head);
travel(head);
head = pop(head);
travel(head); return ;
}

运行结果为:

创建栈
验证是否为空: 栈为空
验证进栈 验证栈顶元素
top =
验证出栈 站为空

python算法与数据结构-栈(43)的更多相关文章

  1. Python算法与数据结构--求所有子数组的和的最大值

    Python算法与数据结构--求所有子数组的和的最大值 玄魂工作室-玄魂 玄魂工作室秘书 玄魂工作室 昨天 题目:输入一个整形数组,数组里有正数也有负数.数组中连续的一个或多个整数组成一个子数组,每个 ...

  2. python算法与数据结构-算法介绍(31)

    一.算法和数据结构 什么是算法和数据结构?如果将最终写好运行的程序比作战场,我们程序员便是指挥作战的将军,而我们所写的代码便是士兵和武器. 那么数据结构和算法是什么?答曰:兵法!故,数据结构和算法是一 ...

  3. python算法与数据结构-队列(44)

    一.队列的介绍 队列的定义:队列是一种特殊的线性表,只允许在表的头部(front处)进行删除操作,在表的尾部(rear处)进行插入操作的线性数据结构,这种结构就叫做队列.进行插入操作的一端称为队尾,进 ...

  4. python算法与数据结构-单链表(38)

    一.链表 链表是一种物理存储单元上非连续.非顺序的存储结构,数据元素的逻辑顺序是通过链表中的指针链接次序实现的.链表由一系列结点(链表中每一个元素称为结点)组成,结点可以在运行时动态生成.每个结点包括 ...

  5. python算法与数据结构-什么是数据结构

    一.什么是数据结构 数据结构,直白地理解,就是研究数据的存储方式. 我们知道,数据存储只有一个目的,即为了方便后期对数据的再利用,就如同我们使用数组存储 {1,2,3,4,5} 是为了后期取得它们的值 ...

  6. python算法与数据结构-数据结构中常用树的介绍(45)

    一.树的定义 树是一种非线性的数据结构,是由n(n >=0)个结点组成的有限集合.如果n==0,树为空树.如果n>0,树有一个特定的结点,根结点根结点只有直接后继,没有直接前驱.除根结点以 ...

  7. python算法与数据结构-二叉树的代码实现(46)

    一.二叉树回忆 上一篇我们对数据结构中常用的树做了介绍,本篇博客主要以二叉树为例,讲解一下树的数据结构和代码实现.回顾二叉树:二叉树是每个节点最多有两个子树的树结构.通常子树被称作“左子树”(left ...

  8. python算法与数据结构-冒泡排序算法(32)

    一.冒泡排序介绍 冒泡排序(英语:Bubble Sort)是一种简单的排序算法.它重复地遍历要排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来.遍历数列的工作是重复地进行直到没有再需要 ...

  9. python算法与数据结构-选择排序算法(33)

    一.选择排序的介绍 选择排序(Selection sort)是一种简单直观的排序算法.首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,然后,再从剩余未排序元素中继续寻找最小(大)元素, ...

随机推荐

  1. java中用反射访问私有方法和私有成员[转]

    转自: http://zhouyangchenrui.iteye.com/blog/470521 java的反射可以绕过访问权限,访问到类的私有方法和成员.可能这点会引起安全性的讨论.反射的使用帮助解 ...

  2. WPF 3D Transparency Depth-Order Sorting

    原文:WPF 3D Transparency Depth-Order Sorting   Just a quick post here - When making WPF 3D apps, trans ...

  3. 重构qDebug()<<,使log输出到文件

    重构qDebug()<<,使log输出到文件 #include <QProcessEnvironment> #include <QDateTime> #includ ...

  4. WPF XAML中 Storyboard.TargetProperty设置TransformGroup指定的变换"RenderTransform.Children

    <Grid x:Name="xx" RenderTransformOrigin="0.5,0.5"> <Grid.RenderTransfor ...

  5. HDU 5073 Galaxy(Anshan 2014)(数学推导,贪婪)

    Galaxy Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 262144/262144 K (Java/Others) Total S ...

  6. SIIA CODIE AWARDS 2017

    Business Technology Best Advertising or Campaign Management Platform Albert, Albert Choozle, Choozle ...

  7. LeetCode 36 Sudoku Solver

    Write a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indicated by th ...

  8. 使用HANDLE_MSG宏简化Win32应用的开发

    http://blog.csdn.net/daiyutage/article/details/17241161 Win32应用中的回调函数WndProc用于接收Windows向应用程序直接发送的消息, ...

  9. sql 1=1

    大多数时候是为了sql拼写方便而加的条件从执行任务来看,不影响性能  

  10. jquery获取选中的值和设置单选扭选中

    <!DOCTYPE html><html><head><meta http-equiv="Content-Type" content=&q ...