四年级下册数学期末考试题_数据结构期末考试题
数据结构期末考试题涉及多个知识点,包括但于数组、链表、栈、队列、树、图、排序算法、查找算法等。下面我把提供典型问题类型及解答示例,帮助你准备考试:
1. 数组问题
问题示例:编写函数,找出数组中重复数字。
解答:
```python
def find_duplicate(nums):
seen = set()
for num in nums:
if num in seen:
return num
seen.add(num)
return None
```
2. 链表问题
问题示例:编写函数,反转单链表。
解答:
```python
class ListNode:
def __init__(self, val=, next=None):
self.val = val
self.next = next
def reverse_list(head):
prev = None
current = head
while current:
next_node = current.next
current.next = prev
prev = current
current = next_node
return prev
```
3. 栈问题
问题示例:实现栈,支持push、pop、peek和isEmpty操作。
解答:
```python
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
if not self.isEmpty():
return self.items.pop()
return None
def peek(self):
if not self.isEmpty():
return self.items[-1]
return None
def isEmpty(self):
return len(self.items) ==
# 使用示例
s = Stack()
s.push(1)
s.push(2)
print(s.peek()) # 输出: 2
print(s.pop()) # 输出: 2
print(s.isEmpty()) # 输出: False
```
4. 树问题
问题示例:实现二叉树前序遍历。
解答:
```python
class TreeNode:
def __init__(self, val=, left=None, right=None):
self.val = val
self.left = left
self.right = right
def preorder_traversal(root):
if root is None:
return []
return [root.val] + preorder_traversal(root.left) + preorder_traversal(root.right)
# 使用示例
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
print(preorder_traversal(root)) # 输出: [1, 2, 4, 5, 3]
```
5. 排序算法
问题示例:实现快速排序算法。
解答:
```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)
# 使用示例
print(quicksort([3, 6, 8, 1, 1, 2, 1])) # 输出: [1, 1, 2, 3, 6, 8, 1]
```
6. 查找算法
问题示例:实现二分查找算法。
解答:
```python
def binary_search(arr, target):
low, high = , 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
# 使用示例
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(binary_search(arr, 4)) # 输出: 3
print(binary_search(arr, 1)) # 输出: -1
```
示例应该能够帮助你复习和准备数据结构考试。记得理解和掌握每个算法工作原理、时间复杂度和空间复杂度,适用场景。