链表系列一>两两交换链表中的结点

目录

题目:

链接: link

解析:

代码:

java 复制代码
/**
 * 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 newHead = new ListNode(0);
        newHead.next = head;
        ListNode prev = newHead;
        ListNode cur = prev.next, next = cur.next,Nnext = next.next;

        while(cur != null && next != null){
            //交换节点
            prev.next = next;
            next.next = cur;
            cur.next = Nnext;
            

            //交换之后继续往后走
            prev = cur;
            cur = Nnext;
            if(cur != null)
                next = cur.next;
            if(next != null)
                Nnext = next.next;

        }
        return newHead.next;
    }
}
相关推荐
PAK向日葵1 小时前
【算法导论】如何攻克一道Hard难度的LeetCode题?以「寻找两个正序数组的中位数」为例
c++·算法·面试
爱装代码的小瓶子2 小时前
数据结构之队列(C语言)
c语言·开发语言·数据结构
爱喝矿泉水的猛男3 小时前
非定长滑动窗口(持续更新)
算法·leetcode·职场和发展
YuTaoShao3 小时前
【LeetCode 热题 100】131. 分割回文串——回溯
java·算法·leetcode·深度优先
YouQian7724 小时前
Traffic Lights set的使用
算法
go54631584655 小时前
基于深度学习的食管癌右喉返神经旁淋巴结预测系统研究
图像处理·人工智能·深度学习·神经网络·算法
aramae5 小时前
大话数据结构之<队列>
c语言·开发语言·数据结构·算法
大锦终5 小时前
【算法】前缀和经典例题
算法·leetcode
想变成树袋熊6 小时前
【自用】NLP算法面经(6)
人工智能·算法·自然语言处理
cccc来财6 小时前
Java实现大根堆与小根堆详解
数据结构·算法·leetcode