【算法】【线性表】【链表】Swap Nodes in Pairs 两两交换链表中的节点
1 题目
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Example 1:
Input: head = [1,2,3,4]
Output: [2,1,4,3]
Example 2:
Input: head = []
Output: []
Example 3:
Input: head = [1]
Output: [1]
Constraints:
- The number of nodes in the list is in the range
[0, 100]
. 0 <= Node.val <= 100
2 解答
这个就比较得心应手了,加个头节点:
/** * 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 preNode = new ListNode(0); preNode.next = head; // node永远指向两个节点的前一个节点 ListNode node = preNode; while (node != null) { // 第一个节点 ListNode nextOneNode = node.next; if (Objects.isNull(nextOneNode)) break; // 第二个节点 ListNode nextTwoNode = nextOneNode.next; if (Objects.isNull(nextTwoNode)) break; // 交换两个节点 // 第二个节点的尾部给到第一个节点的next nextOneNode.next = nextTwoNode.next; nextTwoNode.next = nextOneNode; node.next = nextTwoNode; node = nextOneNode; } return preNode.next; } }
加油。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了