题目:
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
代码:
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
newhead = ListNode(0)
newhead.next = head
p = newhead
while p.next and p.next.next:
second = p.next
first = p.next.next
p.next = first
second.next = first.next
first.next = second
p = p.next.next
return newhead.next