在这个数字时代,数据结构作为计算机科学的基础,扮演着至关重要的角色。掌握数据结构不仅有助于提升编程能力,还能在解决实际问题时游刃有余。本文将为你呈现一份全面的数据结构刷题集,从入门到精通,带你全解析经典算法实战。
第一部分:数据结构入门
1.1 线性结构
线性结构是数据结构中最基础的部分,主要包括数组、链表和栈。
数组:一种按索引顺序存储元素的数据结构,具有随机访问的特点。
# Python实现数组 arr = [1, 2, 3, 4, 5] print(arr[0]) # 输出:1链表:一种通过指针连接元素的数据结构,分为单向链表、双向链表和循环链表。 “`python
Python实现单向链表
class ListNode: def init(self, value=0, next=None):
self.value = value self.next = next
head = ListNode(1) head.next = ListNode(2) head.next.next = ListNode(3)
def print_list(node):
while node:
print(node.value, end=' ')
node = node.next
print_list(head) # 输出:1 2 3
- **栈**:一种后进先出(LIFO)的数据结构,常见操作包括入栈、出栈和判断栈空。
```python
# 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
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.pop()) # 输出:3
1.2 非线性结构
非线性结构主要包括树和图。
树:一种层次结构,包括根节点和子节点,常见操作包括遍历、查找和插入。 “`python
Python实现树
class TreeNode: def init(self, value=0, left=None, right=None):
self.value = value self.left = left self.right = right
root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) root.left.left = TreeNode(4) root.left.right = TreeNode(5)
- **图**:一种由节点和边组成的数据结构,常见操作包括图的遍历、连通性和最短路径。
```python
# Python实现图
class Graph:
def __init__(self):
self.nodes = {}
self.edges = {}
def add_node(self, node):
self.nodes[node] = []
def add_edge(self, node1, node2):
self.edges[(node1, node2)] = True
self.nodes[node1].append(node2)
self.nodes[node2].append(node1)
def dfs(self, node):
visited = set()
stack = [node]
while stack:
current = stack.pop()
if current not in visited:
visited.add(current)
stack.extend(self.nodes[current])
return visited
graph = Graph()
graph.add_node(1)
graph.add_node(2)
graph.add_node(3)
graph.add_edge(1, 2)
graph.add_edge(1, 3)
print(graph.dfs(1)) # 输出:{1, 2, 3}
第二部分:经典算法解析
2.1 排序算法
排序算法是计算机科学中的基础算法,常见的排序算法有冒泡排序、选择排序、插入排序、快速排序等。
- 冒泡排序:通过比较相邻元素的方式,将较大的元素逐渐移动到数组末尾。 “`python def bubble_sort(arr): n = len(arr) for i in range(n): for j in range(0, n-i-1): if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j]
arr = [64, 34, 25, 12, 22, 11, 90] bubble_sort(arr) print(“Sorted array:”, arr)
- **快速排序**:通过选取一个基准值,将数组分为两部分,然后递归地对这两部分进行快速排序。
```python
def quick_sort(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 quick_sort(left) + middle + quick_sort(right)
arr = [64, 34, 25, 12, 22, 11, 90]
print("Sorted array:", quick_sort(arr))
2.2 搜索算法
搜索算法用于在数据结构中查找特定元素,常见的搜索算法有二分查找、深度优先搜索和广度优先搜索。
二分查找:通过不断缩小查找范围,在有序数组中查找特定元素。 “`python def binary_search(arr, x): low = 0 high = len(arr) - 1 mid = 0
while low <= high:
mid = (high + low) // 2 if arr[mid] < x: low = mid + 1 elif arr[mid] > x: high = mid - 1 else: return midreturn -1
arr = [2, 3, 4, 10, 40] x = 10 result = binary_search(arr, x) if result != -1:
print(f"Element is present at index {result}")
else:
print("Element is not present in array")
- **深度优先搜索(DFS)**:通过递归的方式遍历数据结构,访问每个节点。
```python
def dfs(graph, start):
visited = set()
def visit(node):
if node not in visited:
visited.add(node)
for child in graph[node]:
visit(child)
visit(start)
return visited
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}
print(dfs(graph, 'A')) # 输出:{'A', 'B', 'C', 'F', 'D', 'E'}
第三部分:实战应用
3.1 字典树(Trie)
字典树是一种用于高效存储和检索字符串的数据结构,广泛应用于搜索引擎、拼写检查器等场景。
- Python实现字典树 “`python class TrieNode: def init(self): self.children = {} self.is_end_of_word = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.is_end_of_word = True
def search(self, word):
node = self.root
for char in word:
if char not in node.children:
return False
node = node.children[char]
return node.is_end_of_word
trie = Trie() trie.insert(‘apple’) trie.insert(‘banana’) print(trie.search(‘apple’)) # 输出:True print(trie.search(‘app’)) # 输出:False
### 3.2 哈希表(Hash Table)
哈希表是一种基于散列函数快速检索元素的数据结构,广泛应用于数据库、缓存等场景。
- **Python实现哈希表**
```python
class HashTable:
def __init__(self, size):
self.size = size
self.table = [None] * self.size
def hash(self, key):
return hash(key) % self.size
def insert(self, key, value):
index = self.hash(key)
if self.table[index] is None:
self.table[index] = [(key, value)]
else:
self.table[index].append((key, value))
def search(self, key):
index = self.hash(key)
if self.table[index] is not None:
for k, v in self.table[index]:
if k == key:
return v
return None
hash_table = HashTable(10)
hash_table.insert('apple', 5)
hash_table.insert('banana', 10)
print(hash_table.search('apple')) # 输出:5
print(hash_table.search('banana')) # 输出:10
第四部分:总结
本文从数据结构入门、经典算法解析、实战应用等方面,为你呈现了一份全面的数据结构刷题集。通过学习和实践,相信你能够掌握数据结构和算法,为未来的编程之路奠定坚实的基础。祝你学习愉快!
