设计一个测试程序,通过数组int a[]={7,4,2,9,3,1,5}整体创建一个单链表L;输出单链表L,通过调用以上算法将最大值结点移到最前面成为首结点后,输出单链表L
时间: 2024-11-03 12:17:15 浏览: 17
设计这样的测试程序,我们可以使用两个步骤:首先,我们将给定的整数数组转换成单链表,然后找到并移动最大值到链表的头部。这里是一个简单的Python示例:
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def array_to_linked_list(arr):
head = None
tail = None
for num in arr:
new_node = ListNode(num)
if not head:
head = new_node
tail = new_node
else:
tail.next = new_node
tail = new_node
return head
def find_max_and_move(head):
max_val = head.val
max_node = head
current = head.next
while current:
if current.val > max_val:
max_val = current.val
max_node = current
current = current.next
# Swap the maximum value with the head of the list
temp = head
head.val = max_val
max_node.next = head
head = max_node
return head
# 测试数据
arr = [7, 4, 2, 9, 3, 1, 5]
linked_list = array_to_linked_list(arr)
# 移动最大值到链表头部
new_head = find_max_and_move(linked_list)
current = new_head
while current.next:
print(current.val, end=" -> ")
current = current.next
print(f"-> {current.val}") # 输出新的链表
#
阅读全文