您的位置:首页 > 理论基础 > 数据结构算法

数据结构之栈的定义及python实现

2017-07-10 19:15 302 查看
      栈是一个逻辑结构,通俗的讲,是一个有“纪律”的线性表,栈只允许一端进行插入和删除操作,即“先进后出”规则。如下图所示:



       红箭头代表栈顶,即只允许插入和删除的那一端。绿箭头代表栈底,是固定的,即不允许进行插入和删除的另一端。当这个栈内没有元素时,则此时该栈被称为空栈。同样的,栈也有初始化,判定是否为空,插入(进栈),删除(出栈)等操作。下面是关于栈的python实现。

顺序栈实现:

#coding:utf-8

'''
author:xzfreewind
'''

#顺序存储
class Stack(object):
#初始化一个栈
def __init__(self,size):
self.size = size
self.num = 0
self.stack = []

#获取栈的长度
def getSize(self):
return self.num

#输出栈
def outStack(self):
for l in self.stack:
print l

#进栈
def appendStack(self,value):
if self.num >= self.size:
print "the stack is full"
return
else:
self.stack.append(value)
self.num += 1

#出栈
def popStack(self):
if self.isEmpty():
print "the stack is empty,no element can be output"
return
else:
topElement = self.stack[-1]
self.stack.remove(topElement)
return topElement

def isEmpty(self):
if self.num == 0:
return True
else:
return False

def isFull(self):
if self.num == self.size:
return True
else:
return False

链栈实现:

#链式对象建立
class Node(object):
def __init__(self,vaule,q=0):
self.value = vaule
self.next = q

#链式存储
class chainStack(object):
#初始化链栈
def __init__(self):
self.head = 0

#判断栈是否为空
def isEmpty(self):
if self.head == 0:
return True
else:
return False

#计算栈的长度
def getSize(self):
length = 0
p = self.head
while p != 0:
length += 1
p = p.next
return length

#将数组初始化成栈存储
def initStack(self,list):
self.head = Node(list[0])
node = self.head
for i in list[1:]:
p = Node(i)
p.next = node
node = p

#进栈
def insert(self,value):
if self.head == 0: #如果为空栈,直接插入
self.head = Node(value)
else:
node = Node(value)
node.next = self.head
self.head = node

#出栈
def pop(self):
if self.head == 0: #如果为空栈,提示栈为空
print "the stack is empty"
return
else:
l = self.head.value
self.head = self.head.next
return l

#输出栈
def outStack(self):
if self.head == 0: #如果为空栈,提示栈为空
print "the stack is empty"
return
p = self.head
while p != 0:
print p.value
p = p.next
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构