题目链接

思路

使用一个节点一直位于交换的两个节点的前面一个节点即可

代码

  1. class Solution {
  2. fun swapPairs(head: ListNode?): ListNode? {
  3. if (head?.next == null) return head
  4. val tmpHead = ListNode(0)
  5. var curr = tmpHead
  6. var firstN = head
  7. var secondN = head.next
  8. while (firstN!!.next != null) {
  9. firstN.next = secondN!!.next
  10. secondN.next = firstN
  11. curr!!.next = secondN
  12. curr = firstN
  13. if (firstN.next != null) {
  14. firstN = firstN.next
  15. secondN = firstN!!.next
  16. }
  17. }
  18. return tmpHead.next
  19. }
  20. }