【算法】【线性表】【链表】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;
    }
}
复制代码

加油。

posted @   酷酷-  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示