给你一个链表,请你两两交换相邻节点,你需要真正交换节点本身,而不是修改节点的值。
两两交换示例:
链表 :1->2->3->4
交换后 :2->1->4->3
链表 :1->2->3
交换后: 2->1->3
数据范围:链表长度满足 , 链表上的值满足
# class ListNode: # def __init__(self, x): # self.val = x # self.next = None # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param head ListNode类 # @return ListNode类 # class Solution: def swapLinkedPair(self , head: ListNode) -> ListNode: # write code here new_head = ListNode(0) new_head.next = head node = new_head while node.next is not None: if node.next.next is None: break node_one = node.next node_two = node.next.next node_three = node.next.next.next node_one.next = node_three node_two.next = node_one node.next = node_two node = node_one return new_head.next