class LNode():
def __init__(self, data=None):
self.x = data
self.next = None
def swapPairs(head):
pre = head
while pre.next and pre.next.next:
a = pre.next
b = a.next
pre.next, b.next, a.next = b, a, b.next
pre = a
def print_list(head):
node = head.next
while node:
print(node.x, end=" ")
node = node.next
print()
if __name__ == "__main__":
"""
不带头节点
"""
head = LNode(1)
temp = head
for i in range(1, 6):
new_Node = LNode(i)
temp.next = new_Node
temp = new_Node
print_list(head)
swapPairs(head)
print_list(head)
"""
1 2 3 4 5
2 1 4 3 5
"""
ノート - アルゴリズムとデータ構造:近隣要素のリストを交換します
おすすめ
転載: blog.csdn.net/chen_holy/article/details/91471897
ランキング