24. 两两交换链表中的节点

题目:https://leetcode-cn.com/problems/swap-nodes-in-pairs/

代码:

折叠复制代码
  1. class Solution {
  2. public ListNode swapPairs(ListNode head) {
  3. if (head == null || head.next == null) {
  4. //少于2个节点直接返回
  5. return head;
  6. }
  7. ListNode cur = head;//当前点
  8. ListNode pre = null;//前一个
  9. ListNode next;//下一个
  10. head = head.next;//头部变成第二个
  11. while (cur != null && cur.next != null) {
  12. next = cur.next;
  13. //交换
  14. cur.next = next.next;
  15. next.next = cur;
  16. if (pre != null) {
  17. pre.next = next;
  18. }
  19. //cur后移
  20. pre = cur;
  21. cur = cur.next;
  22. }
  23. return head;
  24. }
  25. }

不同于直接两个值的交换,链表的交换比较麻烦点,可以关注下备注中交换的代码。

链表,对于每个节点来说,由两部分组成:1、节点及节点的属性值。2、节点的链即下一个节点的地址。所以对于链表中两个节点的交换,我们直接修改链即可,即next属性。同时还需要注意不要让链断掉。最好理解的办法就是定义3个变量,前一个值pre,当前值cur,下一个值next,对cur和next进行交换,具体实现参考代码。


觉得内容还不错?打赏个钢镚鼓励鼓励!!👍