《Leetcode of October》24.两两交换链表中的节点

《Leetcode of October》24.两两交换链表中的节点

笨方法

  • 先把链表的值都遍历出来放到列表中
  • 然后两两交换其中相邻的节点
  • 然后再构造一个链表出来 

常规方法

  • 设置一个伪节点,让这个节点指向链表的头节点
  • 然后让头结点等于前驱节点pre
  • 找出第一对要交换的节点
    • node1 = pre.next
    • node2 = pre.next.next
  • 对这三个节点重新链接
    • pre.next = node2
    • node2.next = node1.next
    • node2.next = node1
  • 更新pre的节点然后进行下一波更新
    • pre = node1

《Leetcode of October》24.两两交换链表中的节点

《Leetcode of October》24.两两交换链表中的节点

《Leetcode of October》24.两两交换链表中的节点

《Leetcode of October》24.两两交换链表中的节点

《Leetcode of October》24.两两交换链表中的节点

总结:上面截图清晰的解释了2个节点交换的过程,交换两个节点还需要另外一个前驱节点,因此需要一个伪节点。