03:數據結構 棧、隊列、鏈表與數組

算法其他篇

目錄:

  • 1.1 數據結構中的一些概念
  • 1.2 棧(stack)
  • 1.3 隊列
  • 1.4 鏈表
  • 1.5 python中字典對象實現原理
  • 1.6 數組

1.1 數據結構中的一些概念?????返回頂部

  1、數據結構是什么

      1、簡單來說,數據結果就是設計數據以何種方式存儲在計算機中
      2、比如:列表,集合,與字典等都是一種數據結構
      3、程序 = 數據結構 + 算法

1.2 棧(stack)?????返回頂部

  1、棧的定義

? ? ? ? ? ? ? ? ? 棧是一種數據集合,可以理解為只能在一端進行插入或刪除操作的列表

  2、棧的特點

????????????????? 后進先出(last-in, first-out)

  3、棧的概念

????????????????? 棧頂,棧底

  4、棧的基本操作

????????????????? 進棧(壓棧):push

????????????????? 出棧:pop

????????????????? 取棧頂:gettop

  5、棧的使用匹配括號是否成對出現

def check_kuohao(s):stack = []for char in s:if char in ['(','[','{']:stack.append(char)elif char == ')':if len(stack)>0 and stack[-1] == '(':stack.pop()else:return Falseelif char == ']':if len(stack) > 0 and stack[-1] == '[':stack.pop()else:return Falseelif char == '}':if len(stack) > 0 and stack[-1] == '{':stack.pop()else:return Falseif len(stack) == 0:return Trueelse:return False
print(check_kuohao('(){}{}[]'))  #True
匹配括號是否成對出現

1.3 隊列?????返回頂部

  1、隊列定義

      1、隊列是一個數據集合,僅允許在列表的一端進行插入,另一端進行刪除
      2、插入的一端稱為隊尾(rear),插入動作叫進隊或入隊
      3、進行刪除的一端稱為對頭(front),刪除動作稱為出隊
      4、隊列性質:先進先出(First-in, First-out)
      5、雙向隊列:隊列的兩端都允許進行進隊和出隊操作

  2、對列使用方法

      1、導入: from collectios import deque
      2、創建隊列:queue = deque(li)
      3、進隊: append
      4、出隊: popleft
      5、雙向隊列隊首進隊:appendleft
      6、雙向隊列隊尾出隊:pop

  3、雙向對列原理圖

      1、 環形對列:當對位指針front == Maxsize + 1 時,再進一個位置就自動到0
      2、 實現方法:求余數運算
      3、 隊首指針前進1: front = (front + 1)%MaxSize
      4、 隊尾指針前進1:rear = (rear+1)%MaxSize
      5、 隊空條件:rear == front
      6、 隊滿條件:(rear+1)%MaxSize == front

? ? ? ? ? ? ? ??

1.4 鏈表?????返回頂部

  1、單鏈表

    注:鏈表中每個元素都是一個對象,每個對象稱為一個節點,包含有數據域key和指向下一節點的指針next,通過各個節點間的相互連接,最終串聯成一個鏈表

    

#! /usr/bin/env python
# -*- coding: utf-8 -*-
class Node(object):def __init__(self, item):self.item = itemself.next = Noneclass DLinkList(object):def __init__(self):self._head = Nonedef is_empty(self):return self._head == Nonedef append(self, item):'''尾部追加元素'''node = Node(item)if self.is_empty():self._head = nodeelse:cur = self._headwhile cur.next != None:cur = cur.nextcur.next = nodedef add(self, item):"""頭部插入元素"""node = Node(item)if self.is_empty():self._head = node         # 如果是空鏈表,將_head指向nodeelse:node.next = self._head      # 將node的next指向_head的頭節點self._head = node        # 將_head 指向nodedef travel(self):cur = self._headwhile cur != None:print cur.item,cur = cur.nextprint ""def remove(self, item):"""刪除元素"""if self.is_empty():returnelse:cur = self._headif cur.item == item:# 如果首節點的元素即是要刪除的元素if cur.next == None:  # 如果鏈表只有這一個節點self._head = Noneelse:  # 將_head指向第二個節點self._head = cur.nextreturnwhile cur != None:if cur.next.item == item:cur.next = cur.next.nextbreakcur = cur.nextdef insert(self, pos, item):"""在指定位置添加節點"""if pos <= 0:self.add(item)elif pos > (self.length() - 1):self.append(item)else:node = Node(item)cur = self._headcount = 0# 移動到指定位置的前一個位置while count < (pos - 1):count += 1cur_next = cur.next# 將node的next指向cur的下一個節點cur.next = nodenode.next = cur_nextdef length(self):"""返回鏈表的長度"""cur = self._headcount = 0while cur != None:count += 1cur = cur.nextreturn countif __name__ == '__main__':ll = DLinkList()# 1、將鏈表后面追加三個元素:1,2,3ll.append(1)ll.append(2)ll.append(3)ll.travel()  # 1 2 3# 2、將鏈表頭部插入一個元素:0
    ll.add(0)ll.travel()  # 1 2 3  ==>  0 1 2 3# 3、刪除鏈表中的元素:3ll.remove(3)ll.travel()  # 0 1 2 3  ==>  0 1 2# 4、在鏈表的第2號位置插入元素:8ll.insert(2,8)ll.travel()  # 0 1 2  ==>  0 8 1 2 
單鏈表增刪改查
#! /usr/bin/env python
# -*- coding: utf-8 -*-
class Node(object):def __init__(self, val):self.val = valself.next = Nonedef list_reverse(head):if head == None:return NoneL, R, cur = None, None, head  # 左指針、有指針、游標while cur.next != None:L = R             # 左側指針指向以前右側指針位置R = cur           # 右側指針前進一位指向當前游標位置cur = cur.next    # 游標每次向前進一位R.next = L        # 右側指針指向左側實現反轉cur.next = R          # 當跳出 while 循環時 cur(原鏈表最后一個元素) R(原鏈表倒數第二個元素)return curif __name__ == '__main__':'''原始鏈表:1 -> 2 -> 3 -> 4反轉鏈表:4 -> 3 -> 2 -> 1'''l1 = Node(1)l1.next = Node(2)l1.next.next = Node(3)l1.next.next.next = Node(4)l = list_reverse(l1)print l.val         # 4  反轉后鏈表第一個值4print l.next.val    # 3  第二個值3
鏈表反轉
#! /usr/bin/env python
# -*- coding: utf-8 -*-
class ListNode(object):def __init__(self, val, next=None):self.val = valself.next = next# 歸并法: 對鏈表排序
class Solution:def sortList(self, head):if head is None or head.next is None:return headpre = headslow = head  # 使用快慢指針來確定中點fast = headwhile fast and fast.next:pre = slowslow = slow.nextfast = fast.next.nextleft = headright = pre.nextpre.next = None  # 從中間打斷鏈表left = self.sortList(left)right = self.sortList(right)return self.merge(left, right)def merge(self, left, right):pre = ListNode(-1)first = prewhile left and right:if left.val < right.val:pre.next = leftpre = leftleft = left.nextelse:pre.next = rightpre = rightright = right.nextif left:pre.next = leftelse:pre.next = rightreturn first.nextnode1 = ListNode(4)
node2 = ListNode(3)
node3 = ListNode(2)
node4 = ListNode(1)node1.next = node2
node2.next = node3
node3.next = node4s = Solution()
result = s.sortList(node1)while (result != None):print result.val,    # 1 2 3 4result = result.next
鏈表排序:歸并排序算法實現
#!/usr/bin/env python
# -*- coding:utf-8 -*-
def mergesort(seq):if len(seq) <= 1:return seqmid = int(len(seq) / 2)left = mergesort(seq[:mid])right = mergesort(seq[mid:])return merge(left, right)def merge(left, right):result = []i, j = 0, 0while i < len(left) and j < len(right):if left[i] <= right[j]:result.append(left[i])i += 1else:result.append(right[j])j += 1result += left[i:]result += right[j:]return resultif __name__ == '__main__':seq = [10,4,6,3,8,2,5,7]print mergesort(seq)  # [2, 3, 4, 5, 6, 7, 8, 10]
對python列表排序:歸并排序 對比

  2、雙鏈表

    注:雙鏈表中每個節點有兩個指針:一個指針指向后面節點、一個指向前面節點

    

#! /usr/bin/env python
# -*- coding: utf-8 -*-
class Node(object):"""雙向鏈表節點"""def __init__(self, item):self.item = itemself.next = Noneself.prev = Noneclass DLinkList(object):"""雙向鏈表"""def __init__(self):self._head = Nonedef is_empty(self):"""判斷鏈表是否為空"""return self._head == Nonedef length(self):"""返回鏈表的長度"""cur = self._headcount = 0while cur != None:count += 1cur = cur.nextreturn countdef travel(self):"""遍歷鏈表"""cur = self._headwhile cur != None:print cur.item,cur = cur.nextprint ""def add(self, item):"""頭部插入元素"""node = Node(item)if self.is_empty():# 如果是空鏈表,將_head指向nodeself._head = nodeelse:# 將node的next指向_head的頭節點node.next = self._head# 將_head的頭節點的prev指向nodeself._head.prev = node# 將_head 指向nodeself._head = nodedef append(self, item):"""尾部插入元素"""node = Node(item)if self.is_empty():# 如果是空鏈表,將_head指向nodeself._head = nodeelse:# 移動到鏈表尾部cur = self._headwhile cur.next != None:cur = cur.next# 將尾節點cur的next指向nodecur.next = node# 將node的prev指向curnode.prev = curdef search(self, item):"""查找元素是否存在"""cur = self._headwhile cur != None:if cur.item == item:return Truecur = cur.nextreturn Falsedef insert(self, pos, item):"""在指定位置添加節點"""if pos <= 0:self.add(item)elif pos > (self.length() - 1):self.append(item)else:node = Node(item)cur = self._headcount = 0# 移動到指定位置的前一個位置while count < (pos - 1):count += 1cur = cur.next# 將node的prev指向curnode.prev = cur# 將node的next指向cur的下一個節點node.next = cur.next# 將cur的下一個節點的prev指向nodecur.next.prev = node# 將cur的next指向nodecur.next = nodedef remove(self, item):"""刪除元素"""if self.is_empty():returnelse:cur = self._headif cur.item == item:# 如果首節點的元素即是要刪除的元素if cur.next == None:# 如果鏈表只有這一個節點self._head = Noneelse:# 將第二個節點的prev設置為Nonecur.next.prev = None# 將_head指向第二個節點self._head = cur.nextreturnwhile cur != None:if cur.item == item:# 將cur的前一個節點的next指向cur的后一個節點cur.prev.next = cur.next# 將cur的后一個節點的prev指向cur的前一個節點cur.next.prev = cur.prevbreakcur = cur.nextif __name__ == "__main__":ll = DLinkList()ll.add(1)ll.add(2)# ll.append(3)# ll.insert(2, 4)# ll.insert(4, 5)# ll.insert(0, 6)# print "length:",ll.length()# ll.travel()# print ll.search(3)# print ll.search(4)# ll.remove(1)print "length:",ll.length()ll.travel()
雙鏈表增刪改查
#! /usr/bin/env python
# -*- coding: utf-8 -*-
class Node(object):def __init__(self, item):self.item = itemself.next = Noneself.prev = Noneclass DLinkList(object):def __init__(self):self._head = Nonedef is_empty(self):return self._head == Nonedef append(self, item):node = Node(item)if self.is_empty():self._head = nodeelse:cur = self._headwhile cur.next != None:cur = cur.nextcur.next = nodenode.prev = curdef travel(self):cur = self._headwhile cur != None:print cur.item,cur = cur.nextif __name__ == '__main__':ll = DLinkList()ll.append(1)ll.append(2)ll.append(3)# print ll._head.item              # 打印第一個元素:1# print ll._head.next.item         # 打印第二個元素:2# print ll._head.next.next.item    # 打印第三個元素:3ll.travel()    # 1 2 3
雙鏈表追加和遍歷

1.5 python中字典對象實現原理?????返回頂部

  ? 注:字典類型是Python中最常用的數據類型之一,它是一個鍵值對的集合,字典通過鍵來索引,關聯到相對的值,理論上它的查詢復雜度是 O(1)?

  1、哈希表 (hash tables)

      1.?哈希表(也叫散列表),根據關鍵值對(Key-value)而直接進行訪問的數據結構。

      2.?它通過把key和value映射到表中一個位置來訪問記錄,這種查詢速度非常快,更新也快。

      3.?而這個映射函數叫做哈希函數,存放值的數組叫做哈希表。?

      4.?通過把每個對象的關鍵字k作為自變量,通過一個哈希函數h(k),將k映射到下標h(k)處,并將此對象存儲在這個位置。

  2、具體操作過程

      1.?數據添加:把key通過哈希函數轉換成一個整型數字,然后就將該數字對數組長度進行取余,取余結果就當作數組的下標,
      ? ? ? ? ? ? ? ? ? 將value存儲在以該數字為下標的數組空間里。

      2.?數據查詢:再次使用哈希函數將key轉換為對應的數組下標,并定位到數組的位置獲取value。

  3、{“name”:”zhangsan”,”age”:26} 字典如何存儲的呢??

      1.?比如字典{“name”:”zhangsan”,”age”:26},那么他們的字典key為name、age,假如哈希函數h(“name”) = 1、h(“age”)=3,

      2.?那么對應字典的key就會存儲在列表對應下標的位置,[None, “zhangsan”, None, 26 ]

  4、解決hash沖突

      

  5、python字典操作時間復雜度

      

1.6 數組?????返回頂部

  1、數組定義

      1.?所謂數組,就是相同數據類型的元素按一定順序排列的集合

      2.?在Java等其他語言中并不是所有的數據都能存儲到數組中,只有相同類型的數據才可以一起存儲到數組中。

      3.?因為數組在存儲數據時是按順序存儲的,存儲數據的內存也是連續的,所以他的特點就是尋址讀取數據比較容易,插入和刪除比較困難。

  2、python中list與數組比較

      1.?python中的list是python的內置數據類型,list中的數據類不必相同的,而array的中的類型必須全部相同。

      2.?在list中的數據類型保存的是數據的存放的地址,簡單的說就是指針,并非數據

      3.?這樣保存一個list就太麻煩了,例如list1=[1,2,3,'a']需要4個指針和四個數據,增加了存儲和消耗cpu。

      

?

?

?

?

?

轉載于:https://www.cnblogs.com/xiaonq/p/8574655.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/280974.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/280974.shtml
英文地址,請注明出處:http://en.pswp.cn/news/280974.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

力登:以智能化管理提升數據中心服務能力成熟度

2017年2月28日&#xff0c;由全國信息技術標準化技術委員會信息技術服務分技術委員會指導的《信息技術服務數據中心服務能力成熟度模型》發布&#xff0c;在業界首次提出“數據中心服務能力成熟度”概念&#xff0c;使得數據中心的管理真正實現了數字化和持續優化&#xff0c;是…

基于.NET 7 的 WebTransport 實現雙向通信

Web Transport 簡介WebTransport 是一個新的 Web API&#xff0c;使用 HTTP/3 協議來支持雙向傳輸。它用于 Web 客戶端和 HTTP/3 服務器之間的雙向通信。它支持通過 不可靠的 Datagrams API 發送數據&#xff0c;也支持可靠的 Stream API 發送數據。因為 HTTP/3 使用了基于 UDP…

Django01: 安裝/基礎命令/設置筆記

安裝 按官網版本支持&#xff0c;現在比較適合使用1.11版本。 下載安裝命令 pip3 install django1.11.9 新建項目 django-admin startproject mysite 運行項目 python manage.py runserver 127.0.0.1:8000 運行相關 目錄介紹 mysite/ ├── manage.py # 管理文件 └…

JavaScript校驗網址

gistfile1.txt var linkUrl https://www.baidu.com if( typeof (linkUrl) ! undefined &amp;&amp; linkUrl ! ){var strRegex ^((https|http|ftp|rtsp|mms)?://) ?(([0-9a-z_!~*\().&amp;$%-]: )?[0-9a-z_!~*\().&amp;$%-])? //ftp的user (([0-9]{1,3}.)…

線上問題隨筆記錄數據庫連接池問題

修改方法 轉載于:https://www.cnblogs.com/lvgg/p/8581506.html

數據底座_體驗當今計算機的未來:通過智能底座將您的Galaxy S4變成PC

數據底座Have you ever thought that Smartphones these days are so advanced they could actually replace the PC in your everyday computing life? Today, we here at HTG will review using the Galaxy S4 with the “Smart Dock Multimedia Hub” as a PC replacement.…

如何實現 WPF 代碼查看器控件

如何實現 WPF 代碼查看器控件CodeViewer作者&#xff1a;WPFDevelopersOrg - 驚鏵原文鏈接[1]&#xff1a;https://github.com/WPFDevelopersOrg/WPFDevelopers框架使用.NET40&#xff1b;Visual Studio 2019;代碼展示需要使用到AvalonEdit是基于WPF的代碼顯示控件&#xff0c;…

談大數據也談人工智能 郭為告訴你一個不一樣的神州控股

毋庸置疑&#xff0c;我們深處一個數據無處不在的時代&#xff0c;也就是大數據時代。作為中國智慧城市領導者的神州數碼控股有限公司&#xff08;以下簡稱“神州控股”&#xff09;近年來也在積極布局大數據&#xff0c;不過在神州控股董事局主席郭為看來&#xff0c;神州控股…

Django02: pycharm上配置django

1.setting導入 File-->Setting-->Project-->Project Interface 2.new project 新窗口 圖片畫錯 3.調試 點擊右上角調試

vue-cli中配置sass

https://www.cnblogs.com/rainheader/p/6505366.html轉載于:https://www.cnblogs.com/aidixie/p/10213997.html

php 常用函數

用到就記下來&#xff0c;持續更新......... __call(string $func_name, array args){}public方法不存在 調用此函數 通過pg_系列函數與Postgres 數據庫交互 note: php 取得對象的某一共有屬性&#xff0c;若不存在則 查看是否有get方法(魔術方法) 若有則取get方法的返回值&am…

dropbox_來自提示框:望遠鏡激光瞄準器,Dropbox桌面和Kindle剪輯轉換

dropboxOnce a week we round up some great reader tips and share them with everyone; this week we’re looking at telescope laser sights, syncing your desktop with Dropbox, and converting your Kindle Clippings file. 每周一次&#xff0c;我們收集一些很棒的讀者…

在 EF Core 7 中實現強類型 ID

本文主要介紹 DDD 中的強類型 ID 的概念&#xff0c;及其在 EF 7 中的實現&#xff0c;以及使用 LessCode.EFCore.StronglyTypedId 這種更簡易的上手方式。背景在楊中科老師 B 站的.Net Core 視頻教程[1]其中 DDD 部分講到了強類型 ID&#xff08;Strongly-typed-id&#xff09…

如何快速打造一款高清又極速的短視頻APP?

2019獨角獸企業重金招聘Python工程師標準>>> 整個短視頻的市場規模一直在增長&#xff0c;網絡數據顯示2018年已經突破100億大關&#xff0c;在2019年預測將超過200億。縱觀行業&#xff0c;在生活資訊、美食、搞笑、游戲、美妝等領域&#xff0c;短視頻流量巨大但競…

Django03: django加入APP

使用命令在已有project創建 1.創建 在manage.py同級運行命令 python manage.py startapp app01 2.django中加入app 在settings.py里的INSTALLED_APPS加入app01.apps.App01Config, INSTALLED_APPS [django.contrib.admin,django.contrib.auth,django.contrib.contenttype…

[面經]春季跳槽面筋總結 [2018年3月17]

春季跳槽面筋總結 人人都說金三銀四&#xff0c;由于一些個人的原因&#xff0c;博主也在今年的三月份抽空面了幾家公司&#xff0c;這里來總結下學習到的東西。 先簡單的說下博主的情況&#xff1a; 2015年7月份畢業&#xff0c;到現在加上實習可以算三年工作經驗base武漢&…

如何將Windows 10帳戶還原為本地帳戶(在Windows Store劫持它之后)

If your Windows 10 user account is currently a Microsoft account (by your choice or because you got, one way or another, roped into it) it’s easy to revert it back to a local account if you know where to look. Read on as we show you how. 如果您的Windows 1…

【譯】Dapr 是一個“10倍好”平臺 !?

譯者注在正式閱讀本文之前&#xff0c;我們有必要先了解下什么是“10 倍好”。10 倍好理論最早出自彼得蒂爾的《從 0 到 1》&#xff0c;他說一個新創企業&#xff0c;要想獲得快速成長&#xff0c;其提供的解決方案要比現有方案好 10 倍以上&#xff0c;這個好 10 倍&#xff…

04.jQuery 基本語法筆記

jQuery是什么 jQuery是一個輕量級的、兼容多瀏覽器的JavaScript庫。jQuery使用戶能夠更方便地處理HTML Document、Events、實現動畫效果、方便地進行Ajax交互&#xff0c;能夠極大地簡化JavaScript編程。它的宗旨就是&#xff1a;“Write less, do more.“ jQuery引入到HTML …

1. ReactJS基礎(開發環境搭建)

本文主要介紹通過React官方提供的create-react-app腳手架進行開發環境的搭建。 1.安裝node環境(安裝過程這里不做介紹&#xff0c;可參考其他博文) 在cmd中輸入node -v 如果可以看到相應版本號&#xff0c;說明node環境安裝成功 2.npm全局安裝create-react-app腳手架 3.cmd命令…