第一部分:数据结构与算法
1.1 线性表
主题句:线性表是计算机科学中最基本的数据结构之一,包括顺序表和链表。
支持细节:
顺序表:使用数组实现,优点是访问速度快,但插入和删除操作需要移动大量元素。 “`python class SequentialList: def init(self, capacity):
self.capacity = capacity self.data = [None] * capacity self.size = 0def get(self, index):
if index < 0 or index >= self.size: raise IndexError("Index out of bounds") return self.data[index]def insert(self, index, element):
if index < 0 or index > self.size: raise IndexError("Index out of bounds") for i in range(self.size, index, -1): self.data[i] = self.data[i - 1] self.data[index] = element self.size += 1
# Example usage seq_list = SequentialList(10) seq_list.insert(0, 1) seq_list.insert(1, 2) print(seq_list.get(0)) # Output: 1 print(seq_list.get(1)) # Output: 2
- **链表**:使用节点实现,优点是插入和删除操作灵活,但访问速度较慢。
```python
class ListNode:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, value):
if not self.head:
self.head = ListNode(value)
return
current = self.head
while current.next:
current = current.next
current.next = ListNode(value)
# Example usage
linked_list = LinkedList()
linked_list.append(1)
linked_list.append(2)
print(linked_list.head.value) # Output: 1
print(linked_list.head.next.value) # Output: 2
1.2 栈与队列
主题句:栈和队列是两种特殊的线性表,具有不同的操作规则。
支持细节:
栈:遵循后进先出(LIFO)的原则,主要操作包括入栈(push)和出栈(pop)。 “`python class Stack: def init(self):
self.items = []def is_empty(self):
return len(self.items) == 0def push(self, item):
self.items.append(item)def pop(self):
if not self.is_empty(): return self.items.pop() raise IndexError("Stack is empty")
# Example usage stack = Stack() stack.push(1) stack.push(2) print(stack.pop()) # Output: 2 print(stack.pop()) # Output: 1
- **队列**:遵循先进先出(FIFO)的原则,主要操作包括入队(enqueue)和出队(dequeue)。
```python
class Queue:
def __init__(self):
self.items = []
def is_empty(self):
return len(self.items) == 0
def enqueue(self, item):
self.items.append(item)
def dequeue(self):
if not self.is_empty():
return self.items.pop(0)
raise IndexError("Queue is empty")
# Example usage
queue = Queue()
queue.enqueue(1)
queue.enqueue(2)
print(queue.dequeue()) # Output: 1
print(queue.dequeue()) # Output: 2
第二部分:算法
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]
# Example usage arr = [64, 34, 25, 12, 22, 11, 90] bubble_sort(arr) print(“Sorted array is:”, arr)
- **选择排序**:在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,然后,再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。
```python
def selection_sort(arr):
n = len(arr)
for i in range(n):
min_index = i
for j in range(i+1, n):
if arr[min_index] > arr[j]:
min_index = j
arr[i], arr[min_index] = arr[min_index], arr[i]
# Example usage
arr = [64, 34, 25, 12, 22, 11, 90]
selection_sort(arr)
print("Sorted array is:", arr)
- 插入排序:将一个记录插入到已经排好序的有序表中,从而得到一个新的、记录数增加1的有序表。 “`python def insertion_sort(arr): for i in range(1, len(arr)): key = arr[i] j = i-1 while j >=0 and key < arr[j]: arr[j+1] = arr[j] j -= 1 arr[j+1] = key
# Example usage arr = [64, 34, 25, 12, 22, 11, 90] insertion_sort(arr) print(“Sorted array is:”, arr)
### 2.2 查找算法
**主题句**:查找算法用于在数据结构中查找特定元素。
**支持细节**:
- **顺序查找**:从数组的第一个元素开始,依次将元素与要查找的元素进行比较。
```python
def sequential_search(arr, x):
for i in range(len(arr)):
if arr[i] == x:
return i
return -1
# Example usage
arr = [64, 34, 25, 12, 22, 11, 90]
x = 25
print("Element is present at index", sequential_search(arr, x))
- 二分查找:只适用于有序数组,通过比较中间元素与要查找的元素,逐步缩小查找范围。 “`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 mid return -1
# Example usage arr = [2, 3, 4, 10, 40] x = 10 print(“Element is present at index”, binary_search(arr, x))
## 第三部分:图论
### 3.1 图的表示
**主题句**:图是表示对象之间关系的抽象数据类型,常用的表示方法有邻接矩阵和邻接表。
**支持细节**:
- **邻接矩阵**:使用二维数组表示图,其中元素表示顶点之间的连接关系。
```python
def create_adjacency_matrix(vertices):
matrix = [[0] * len(vertices) for _ in range(len(vertices))]
return matrix
# Example usage
vertices = ["A", "B", "C", "D"]
matrix = create_adjacency_matrix(vertices)
print(matrix)
邻接表:使用链表表示图,每个节点表示一个顶点,节点中的列表表示与该顶点相连的其他顶点。 “`python class AdjacencyList: def init(self):
self.adj_list = {}def add_edge(self, vertex1, vertex2):
if vertex1 not in self.adj_list: self.adj_list[vertex1] = [] if vertex2 not in self.adj_list: self.adj_list[vertex2] = [] self.adj_list[vertex1].append(vertex2) self.adj_list[vertex2].append(vertex1)
# Example usage adj_list = AdjacencyList() adj_list.add_edge(“A”, “B”) adj_list.add_edge(“B”, “C”) print(adj_list.adj_list)
### 3.2 图的遍历
**主题句**:图的遍历算法用于访问图中的所有顶点,常用的遍历算法有深度优先遍历(DFS)和广度优先遍历(BFS)。
**支持细节**:
- **深度优先遍历**:从起始顶点开始,沿着一条路径一直走到尽头,然后回溯并沿着另一条路径继续遍历。
```python
def dfs(graph, start_vertex):
visited = set()
stack = [start_vertex]
while stack:
vertex = stack.pop()
if vertex not in visited:
visited.add(vertex)
print(vertex, end=" ")
for neighbor in graph[vertex]:
if neighbor not in visited:
stack.append(neighbor)
# Example usage
graph = {
"A": ["B", "C"],
"B": ["C", "D"],
"C": ["D"],
"D": []
}
dfs(graph, "A")
广度优先遍历:从起始顶点开始,沿着一条路径一直走到尽头,然后访问与该顶点相连的所有顶点,再沿着另一条路径继续遍历。 “`python def bfs(graph, start_vertex): visited = set() queue = [start_vertex]
while queue:
vertex = queue.pop(0) if vertex not in visited: visited.add(vertex) print(vertex, end=" ") for neighbor in graph[vertex]: if neighbor not in visited: queue.append(neighbor)
# Example usage graph = {
"A": ["B", "C"],
"B": ["C", "D"],
"C": ["D"],
"D": []
} bfs(graph, “A”) “`
