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

目录

题目:

链接: 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;
    }
}
相关推荐
会编程的土豆24 分钟前
日常做题 vlog
数据结构·c++·算法
Omigeq1 小时前
1.4 - 曲线生成轨迹优化算法(以BSpline和ReedsShepp为例) - Python运动规划库教程(Python Motion Planning)
开发语言·人工智能·python·算法·机器人
网络工程小王1 小时前
【大模型(LLM)的业务开发】学习笔记
人工智能·算法·机器学习
y = xⁿ1 小时前
【Leet Code 】滑动窗口
java·算法·leetcode
WBluuue1 小时前
数据结构与算法:二项式定理和二项式反演
c++·算法
nianniannnn1 小时前
力扣104.二叉树的最大深度 110. 平衡二叉树
算法·leetcode·深度优先
_深海凉_1 小时前
LeetCode热题100-只出现一次的数字
算法·leetcode·职场和发展
nianniannnn2 小时前
力扣206.反转链表 92.反转链表II
算法·leetcode·链表
澈2072 小时前
哈希表实战:从原理到手写实现
算法·哈希算法
旖-旎2 小时前
哈希表(存在重复元素||)(4)
数据结构·c++·算法·leetcode·哈希算法·散列表