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

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

题目描述:给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。

示例 1:

输入:head = [1,2,3,4]
输出:[2,1,4,3]

示例 2:

输入:head = []
输出:[]

示例 3:

输入:head = [1]
输出:[1]

提示:

  • 链表中节点的数目在范围 [0, 100] 内
  • 0 <= Node.val <= 100

 需要注意:

  • 在交换两个节点后,需要更新相应的指针
  • 需要特别注意头节点的处理,因为头节点的交换会改变链表的头

核心思路是通过遍历链表,对于每两个相邻的节点进行交换。在交换节点时,需要注意处理头节点以及更新相应的指针。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode temp = head;
        ListNode pre = temp;
        ListNode cur = null;
        ListNode nex = null;
        while (temp != null && temp.next != null) {
            pre = temp;

            if (temp == head) {
                cur = temp;
                nex = temp.next;

                cur.next = nex.next;
                nex.next = cur;
                head = nex;
            } else if (temp.next.next == null) break;
            else {
                cur = temp.next;
                nex = cur.next;

                cur.next = nex.next;
                pre.next = nex;
                nex.next = cur;
                temp = temp.next.next;
            }
        }
        return head;
    }
}

相关推荐

  1. leetcode24. 交换节点

    2024-04-28 14:58:02       47 阅读
  2. LeetCode [24] 交换节点

    2024-04-28 14:58:02       44 阅读
  3. Leetcode24. 交换节点

    2024-04-28 14:58:02       43 阅读
  4. LeetCode24.交换节点

    2024-04-28 14:58:02       40 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-28 14:58:02       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-28 14:58:02       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-28 14:58:02       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-28 14:58:02       18 阅读

热门阅读

  1. 华企盾的面试流程,华企盾招聘流程

    2024-04-28 14:58:02       13 阅读
  2. 2024.4.27每日一题

    2024-04-28 14:58:02       13 阅读
  3. day04--react中state的简化

    2024-04-28 14:58:02       13 阅读
  4. axios下载接口后端返回了json但前端得到的是blob

    2024-04-28 14:58:02       11 阅读
  5. LeetCode //C - 18. 4Sum

    2024-04-28 14:58:02       11 阅读
  6. 2023-2024年AI+跨境电商行业报告合集(精选47份)

    2024-04-28 14:58:02       12 阅读
  7. Kafka

    2024-04-28 14:58:02       10 阅读
  8. MySQL数据库中Delete语句和Truncate table 语句的区别

    2024-04-28 14:58:02       12 阅读
  9. vue+vue-qr生成带logo的二维码并自动下载

    2024-04-28 14:58:02       11 阅读
  10. JDK安装

    2024-04-28 14:58:02       9 阅读