(线性表)试编写算法将线性表就地逆置,以链式存储结构实现。 PS:输入以eof结束
时间: 2024-04-08 17:28:58 浏览: 71
好的,下面是将链式存储结构的线性表就地逆置的算法实现:
```python
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
def reverse_list(head):
if head is None or head.next is None:
return head
pre = None
cur = head
while cur:
next_node = cur.next
cur.next = pre
pre = cur
cur = next_node
return pre
# 测试代码
def print_list(head):
cur = head
while cur:
print(cur.data, end=" ")
cur = cur.next
print()
def create_list():
head = Node()
cur = head
while True:
try:
data = input()
if data == "eof":
break
new_node = Node(data)
cur.next = new_node
cur = new_node
except EOFError:
break
return head.next
if __name__ == "__main__":
head = create_list()
print("原始链表:")
print_list(head)
new_head = reverse_list(head)
print("逆置后的链表:")
print_list(new_head)
```
你可以逐行输入线性表的元素,使用 "eof" 结束输入。然后算法会输出原始链表和逆置后的链表。
请注意,这只是其中一种实现方式,还有其他方法可以实现线性表的就地逆置。
阅读全文