iT邦幫忙

2021 iThome 鐵人賽

DAY 10
0
Software Development

算法30天系列 第 10

Day.10 Stack

Stack(堆疊)是一種後進先出(LIFO)的資料結構

看一下圖
Alt text

註:圖源

你可以想像一下在廚房洗碗,盤子在洗手臺堆起來,你一定是從最上面開始開,不會從最底。
或者是瀏覽器回到上一頁的功能,愈近的記錄會愈早讀到,生活中還有滿多stack的應用~

Stack觀念跟程式都不難,以下來實作一下
這邊會用slice來做,push資料的時候append到slice裡面,pop的時候取slice最後的值就可以了。

程式:

type Stack struct {
	nodes []int
}

func (s *Stack) Push(val int) {
	s.nodes = append(s.nodes, val)
}

func (s *Stack) Pop() int {
	if len(s.nodes) == 0 {
		return 0
	}

	res := s.nodes[len(s.nodes)-1]
	s.nodes = s.nodes[0 : len(s.nodes)-1]

	return res
}

學完了,明天就來寫leetcode XD~


上一篇
Day.9 Add Two Numbers
下一篇
Day.11 Decode String
系列文
算法30天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言