假设线性表(a1,a2,a3,…an)采用带头结点的单链表存储,请设计算法函数linklist reverse(linklist head), 将带头结点的单链表head就地倒置,使表变成(an,an-1,…a3.a2,a1)。并构造测试用例进行测试。
时间: 2024-05-14 15:11:50 浏览: 118
好的,我明白了。以下是算法函数linklist reverse的代码:
```python
def reverse(head):
"""
将带头结点的单链表head就地倒置,使表变成(an,an-1,…a3.a2,a1)
"""
if head is None or head.next is None:
return head
pre = None
curr = head.next
while curr:
next_node = curr.next
curr.next = pre
pre = curr
curr = next_node
head.next = pre
return head
```
构造测试用例:
```python
class Node:
def __init__(self, val=None):
self.val = val
self.next = None
def create_linked_list(nodes):
"""
根据给定的节点列表创建带头结点的单链表
"""
head = Node()
curr = head
for val in nodes:
curr.next = Node(val)
curr = curr.next
return head
def linked_list_to_list(head):
"""
将带头结点的单链表转化为列表
"""
res = []
curr = head.next
while curr:
res.append(curr.val)
curr = curr.next
return res
def test_reverse():
nodes1 = [1, 2, 3, 4]
head1 = create_linked_list(nodes1)
assert linked_list_to_list(reverse(head1)) == [4, 3, 2, 1]
nodes2 = [1]
head2 = create_linked_list(nodes2)
assert linked_list_to_list(reverse(head2)) == [1]
nodes3 = []
head3 = create_linked_list(nodes3)
assert linked_list_to_list(reverse(head3)) == []
print("所有测试用例通过")
if __name__ == "__main__":
test_reverse()
```
希望这些可以帮到您!
阅读全文