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
"""
笔记 - 算法与数据结构:链表交换相邻元素
最新推荐文章于 2023-02-12 20:35:26 发布