链表递归

难度中等

题目描述

image.png

解题思路

思路一

非递归

思路二

递归
老师和同学玩游戏,同学们站成一排,依次是小明,小红,小王等等等。。。。。
老师把玩法告诉小明,于是聪明的小明决定和小红互换位置,然后把玩法告诉小王,然后小王又和小明做一样的事。。。。。。

作者:acnesu
链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs/solution/zhe-di-gui-wo-kan-sha-liao-by-acnesu/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Code

  1. public ListNode swapPairsI(ListNode head) {
  2. ListNode pre = new ListNode(0);
  3. pre.next = head;
  4. ListNode temp = pre;
  5. while (temp.next != null && temp.next.next != null) {
  6. ListNode start = temp.next;
  7. ListNode end = temp.next.next;
  8. temp.next = end;
  9. start.next = end.next;
  10. end.next = start;
  11. temp = start;
  12. }
  13. return pre.next;
  14. }
  15. public ListNode swapPairsII(ListNode head) {
  16. if (head == null || head.next == null) {
  17. return head;
  18. }
  19. ListNode next = head.next;
  20. // next 后面就不管了,直接递归。。。。
  21. next.next = swapPairsII(next.next);
  22. //下面两行代码是交换链表两个节点
  23. head.next = next.next;
  24. next.next = head;
  25. // 交换后,next 就是前面的节点
  26. return next;
  27. }