# encoding=UTF-8
"""
反转列表
"""
def reverse(S, start, stop):
# 使用递归实现
if start < stop - 1:
S[start], S[stop-1] = S[stop-1], S[start]
reverse(S, start+1, stop-1)
def reverse_iterative(S):
# 使用循环实现
start, stop = 0, len(S)
while start < stop - 1:
S[start], S[stop-1] = S[stop-1], S[start]
start, stop = start+1, stop-1
if __name__ == '__main__':
s = [4, 3, 6, 2, 8, 9, 5]
reverse(s, 0, len(s))
print(s)
s = [4, 3, 6, 2, 8, 9, 5]
reverse_iterative(s)
print(s)
反转列表数据
最新推荐文章于 2024-04-13 14:15:00 发布