Python数据结构与算法实现总结(python数据结构知乎)

学习数据结构与算法是编程的核心基础之一。以下是使用Python实现常见数据结构与算法的总结:

一、数据结构

1. 链表

  • 节点定义

python

class Node:

def __init__(self, data):

self.data = data

self.next = None

  • 链表操作:插入、删除、遍历。

2. 栈

  • 实现(后进先出):

python

class Stack:

def __init__(self):

self.items = []

def push(self, item):

self.items.append(item)

def pop(self):

return self.items.pop()

def is_empty(self):

return len(self.items) == 0

3. 队列

  • 实现(先进先出,使用链表):

python

class Queue:

def __init__(self):

self.head = None

self.tail = None

def enqueue(self, data):

new_node = Node(data)

if self.tail is None:

self.head = self.tail = new_node

else:

self.tail.next = new_node

self.tail = new_node

def dequeue(self):

if self.head is None:

return None

data = self.head.data

self.head = self.head.next

if self.head is None:

self.tail = None

return data

4. 树

  • 二叉树节点

python

class TreeNode:

def __init__(self, val):

self.val = val

self.left = None

self.right = None

  • 遍历(前序、中序、后序、层序):

python

# 前序遍历(递归)

def preorder(root):

if root:

print(root.val)

preorder(root.left)

preorder(root.right)


# 层序遍历(队列)

from collections import deque

def level_order(root):

if not root:

return []

queue = deque([root])

result = []

while queue:

level = []

for _ in range(len(queue)):

node = queue.popleft()

level.append(node.val)

if node.left:

queue.append(node.left)

if node.right:

queue.append(node.right)

result.append(level)

return result

5. 图

  • 邻接表表示

python

graph = {

'A': ['B', 'C'],

'B': ['D'],

'C': ['E'],

'D': ['F'],

'E': [],

'F': []

}

  • 遍历

python

# DFS(递归)

def dfs(graph, node, visited):

if node not in visited:

print(node)

visited.add(node)

for neighbor in graph[node]:

dfs(graph, neighbor, visited)


# BFS(队列)

from collections import deque

def bfs(graph, start):

visited = set()

queue = deque([start])

visited.add(start)

while queue:

node = queue.popleft()

print(node)

for neighbor in graph[node]:

if neighbor not in visited:

visited.add(neighbor)

queue.append(neighbor)

6. 堆

  • 使用heapq模块(最小堆):

python

import heapq

heap = []

heapq.heappush(heap, 3)

heapq.heappush(heap, 1)

print(heapq.heappop(heap)) # 输出1

二、算法

1. 排序算法

  • 快速排序

python

def quicksort(arr):

if len(arr) <= 1:

return arr

pivot = arr[len(arr)//2]

left = [x for x in arr if x < pivot]

middle = [x for x in arr if x == pivot]

right = [x for x in arr if x > pivot]

return quicksort(left) + middle + quicksort(right)

  • 归并排序

python

def merge_sort(arr):

if len(arr) <= 1:

return arr

mid = len(arr) // 2

left = merge_sort(arr[:mid])

right = merge_sort(arr[mid:])

return merge(left, right)


def merge(left, right):

result = []

i = j = 0

while i < len(left) and j < len(right):

if left[i] < right[j]:

result.append(left[i])

i += 1

else:

result.append(right[j])

j += 1

result.extend(left[i:])

result.extend(right[j:])

return result

2. 查找算法

  • 二分查找

python

def binary_search(arr, target):

low, high = 0, len(arr)-1

while low <= high:

mid = (low + high) // 2

if arr[mid] == target:

return mid

elif arr[mid] < target:

low = mid + 1

else:

high = mid - 1

return -1

3. 动态规划

  • 斐波那契数列

python

def fib(n):

a, b = 0, 1

for _ in range(n):

a, b = b, a + b

return a

  • 0-1背包问题

python

def knapsack(weights, values, capacity):

n = len(weights)

dp = [[0]*(capacity+1) for _ in range(n+1)]

for i in range(1, n+1):

for w in range(1, capacity+1):

if weights[i-1] > w:

dp[i][w] = dp[i-1][w]

else:

dp[i][w] = max(dp[i-1][w], values[i-1] + dp[i-1][w - weights[i-1]])

return dp[n][capacity]

三、总结

  • 时间复杂度:理解各算法的时间复杂度(如快速排序平均O(n log n),冒泡排序O(n^2))。
  • 空间复杂度:如归并排序需要额外空间,原地排序更高效。
  • 应用场景:根据问题特点选择合适的数据结构与算法(如频繁查找用哈希表,有序数据用二分查找)。

通过实践和刷题(如LeetCode)加深理解,掌握不同场景下的最优解。

相关文章

Python程序员必备:数据结构与算法一览表

之前,笔者曾经在《Python和Ruby大PK,到底谁才是开发者最喜欢的语言》一文中,曾经向网友发起了Python VS Ruby VS 其它的投票活动,结果票数一面倒的全部投给了Python。Ope...

Python常用算法学习(4) 数据结构(原理+代码)-最全总结

数据结构简介1,数据结构  数据结构是指相互之间存在着一种或多种关系的数据元素的集合和该集合中数据元素之间的关系组成。简单来说,数据结构就是设计数据以何种方式组织并存贮在计算机中。比如:列表,集合与字...

Python进阶 - day1:深入理解数据结构

以下是“Python进阶 - Day 1:深入理解数据结构”的详细学习内容,包含带注释的代码示例,帮助你掌握列表、字典、集合、元组的高级用法,并完成指定练习任务。学习内容列表(List)高级用法列表推...

实时可视化数据结构与算法让代码动起来

Stay 是一个专注于数据结构与算法可视化的编程学习网站,可将代码执行过程转化为生动流畅的动画,帮助学习者更直观地理解复杂概念。以下是其具体介绍:支持的语言及数据结构与算法支持的语言 :目前支持 Py...

Python中的数据结构(python主要数据结构)

在Python中,有几种预定义的数据结构,也称为内置数据类型。这些数据结构允许您有效地存储和组织数据,以进行各种操作,如搜索,排序或访问特定元素。列表列表是一个有序的项目(元素)集合。列表是可变的,这...