题目:
对于一组给定链表,交换相邻结点。并返回头结点
示例:
例如: 1->2->3->4
返回: 2->1->4->3.
可以用3个指针:用head指向需要交换结点的前一个结点;用n1指向需要交换的第一个结点;n2指向需要交换的第二个结点。
然后不断交换n1、n2的位置即可。
class LNode:
def __init__(self, elem):
self.elem = elem
self.next = None
def swapPairs(head):
if head is None or head.next is None: # 如果输入的链表是空或者只有一个结点,直接返回当前结点
return head
new = LNode(0) #新建一个表头,其中的元素为0
new.next = head
head = new
while head.next is not None and head.next.next is not None:
n1 = head.next
n2 = head.next.next
# 交换n1、n2的指向
head.next = n2
n1.next = n2.next
n2.next = n1
# 将head指向此时的n1
head = n1
return new.next
if __name__ == "__main__":
head = LNode(1)
p1 = LNode(2)
p2 = LNode(3)
p3 = LNode(4)
head.next = p1
p1.next = p2
p2.next = p3
p = swapPairs(head)
while p:
print(p.elem)
p = p.next