设有一线性表e=(e1 , e2 , … , en-1 , en),其逆线性表定义为e'=( en , en-1 , … , e2 , e1),请设计一个算法,将线性表逆置,要求逆线性表仍占用原线性表的空间,并且用顺序表和单链表两种方法来表示,写出不同的处理函数。
时间: 2024-10-14 22:12:47 浏览: 32
对于顺序表:
```python
def reverseSequentialList(SequentialList):
n = len(SequentialList)
for i in range(n // 2): # 从两端向中间遍历并交换元素
SequentialList[i], SequentialList[n - i - 1] = SequentialList[n - i - 1], SequentialList[i]
return SequentialList
# 示例:
original_list = [1, 2, 3, 4, 5]
reversed_sequential_list = reverseSequentialList(original_list)
```
对于单链表:
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverseLinkedList(head):
prev = None
current = head
while current is not None:
next_temp = current.next
current.next = prev
prev = current
current = next_temp
return prev # 返回新的头节点,原来的尾部变成了新链表的头
# 示例:
# 定义链表节点
head = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5)))))
reversed_head = reverseLinkedList(head)
```
处理函数`reverseSequentialList`用于顺序表,而`reverseLinkedList`用于单链表,它们都实现了线性表的逆置操作。
阅读全文