資料結構之棧

2021-08-10 17:46:40 字數 2619 閱讀 4245

今天我們繼續聊聊棧(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):

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 #include /**

* c 語言: 陣列實現的棧,只能儲存int資料。

* * @author skywang

* @date 2013/11/07

*/// 儲存資料的陣列

static int *arr=null;

// 棧的實際大小

static int count;

// 建立「棧」,預設大小是12

int create_array_stack(int sz)

return 0;

}// 銷毀「棧」

int destroy_array_stack()

return 0;

}// 將val新增到棧中

void push(int val)

// 返回「棧頂元素值」

int peek()

// 返回「棧頂元素值」,並刪除「棧頂元素」

int pop()

// 返回「棧」的大小

int size()

// 返回「棧」是否為空

int is_empty()

// 列印「棧」

void print_array_stack()

printf("stack size()=%d\n", size());

int i=size()-1;

while (i>=0)

}void main()

(1)

題目:面試題7-用兩個棧實現佇列(劍指offer)

用兩個棧來實現乙個佇列,完成佇列的push和pop操作。 佇列中的元素為int型別。

棧:後進先出(lifo); 

佇列:先進先出(fifo). 

入隊:將元素進棧a 

出隊:判斷棧b是否為空,如果為空,則將棧a中所有元素pop,並push進棧b,棧b出棧; 

如果不為空,棧b直接出棧

python 實現:

# -*- coding:utf-8 -*-

class solution:

def __init__(self):

self.stack1 =

self.stack2 =

def push(self, node):

# write code here

def pop(self):

# return xx

if self.stack2 == :

while self.stack1:

return self.stack2.pop()

資料結構之棧結構

棧結構是一種filo first in last out 的批量資料儲存結構。其特點是先進後出,後來者居上 棧的基本屬性 棧記憶體 棧頂標記 棧的當前元素個數 萬金油屬性 size 棧的基本操作 萬金油的的操作 根據實現的不同將棧結構分為兩種 1.鏈式棧 2.陣列 利用有表頭鍊錶的頭插法來完成棧的功...

資料結構之棧

4.8.2 四則運算表示式求值 程式如下所示 include include include 定義結點型別 typedef struct node node,pnode 定義棧的抽象資料型別 typedef struct stack stack,pstack 函式宣告 對棧進行初始化的函式 void...

資料結構之棧

資料結構之棧 本文討論棧的陣列實現。棧需要有如下幾個屬性 棧的容量 capacity 棧頂指標 儲存棧元素的陣列 根據這幾個屬性可以定義乙個棧結構體 struct stackrecord 然後定義棧的操作,一般可以包含如下幾個 棧的建立 stack createstack int size 棧的銷毀...