用python完成以下题目代码 题目一:链表实现 创建一个 `LinkedList` 实例,进行以下操作: - 在链表末尾添加节点值为 1。 - 在链表末尾添加节点值为 2。 - 在链表末尾添加节点值为 3。 - 打印链表中所有节点的值。 - 删除节点值为 2 的节点。 - 打印链表中所有节点的值。 题目二:二分查找: 实现一个函数 `binary_search`,接受一个已排序的整数列表 `nums` 和一个目标值 `target`,返回目标值在列表中的索引位置。如果目标值不存在于列表中,则返回 -1。 要求使用迭代方式实现二分查找算法。 题目三:选择排序 实现一个函数 `selection_sort`,接受一个整数列表作为参数,并返回排序后的列表。 要求使用选择排序算法对列表进行排序。 题目四:图的广度优先搜索 实现一个函数 `dfs`,接受一个有向图和起始节点作为参数,并返回从起始节点开始的深度优先搜索遍历结果。 要求使用递归方式实现深度优先搜索算法。
时间: 2024-02-06 15:09:00 浏览: 69
题目一:
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def addNode(self, data):
newNode = Node(data)
if self.head is None:
self.head = newNode
else:
current = self.head
while current.next is not None:
current = current.next
current.next = newNode
def printList(self):
current = self.head
while current is not None:
print(current.data)
current = current.next
def deleteNode(self, data):
current = self.head
if current is not None and current.data == data:
self.head = current.next
current = None
return
else:
while current is not None:
if current.data == data:
break
prev = current
current = current.next
if current == None:
return
prev.next = current.next
current = None
# Create a linked list instance
linkedList = LinkedList()
# Add nodes to the linked list
linkedList.addNode(1)
linkedList.addNode(2)
linkedList.addNode(3)
# Print all nodes in the linked list
linkedList.printList()
# Delete the node with value 2
linkedList.deleteNode(2)
# Print all nodes in the linked list again
linkedList.printList()
```
题目二:
```python
def binary_search(nums, target):
left = 0
right = len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
elif nums[mid] > target:
right = mid - 1
else:
left = mid + 1
return -1
# Example usage
nums = [1, 3, 5, 7, 9]
target = 5
result = binary_search(nums, target)
print(result)
```
题目三:
```python
def selection_sort(nums):
for i in range(len(nums)):
min_index = i
for j in range(i+1, len(nums)):
if nums[j] < nums[min_index]:
min_index = j
nums[i], nums[min_index] = nums[min_index], nums[i]
return nums
# Example usage
nums = [64, 25, 12, 22, 11]
sorted_nums = selection_sort(nums)
print(sorted_nums)
```
题目四:
```python
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
print(start)
for next_node in graph[start] - visited:
dfs(graph, next_node, visited)
return visited
# Example usage
graph = {'A': set(['B', 'C']),
'B': set(['A', 'D', 'E']),
'C': set(['A', 'F']),
'D': set(['B']),
'E': set(['B', 'F']),
'F': set(['C', 'E'])}
dfs(graph, 'A')
```
阅读全文