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

目录

题目:

链接: 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;
    }
}
相关推荐
Swift社区20 小时前
LeetCode 400 - 第 N 位数字
算法·leetcode·职场和发展
fengfuyao98520 小时前
BCH码编译码仿真与误码率性能分析
算法
小白不想白a21 小时前
每日手撕算法--哈希映射/链表存储数求和
数据结构·算法
剪一朵云爱着21 小时前
力扣2080. 区间内查询数字的频率
算法·leetcode
落日漫游21 小时前
数据结构笔试核心考点
java·开发语言·算法
Doro再努力21 小时前
数据结构04:力扣顺序表3道例题解题思路与代码实现
c语言·数据结构
HY小海1 天前
【C++】AVL树实现
开发语言·数据结构·c++
workflower1 天前
Fundamentals of Architectural Styles and patterns
开发语言·算法·django·bug·结对编程
花月C1 天前
高效查找数据的数据结构—MySQL 索引
数据结构·数据库·mysql
仰泳的熊猫1 天前
LeetCode:701. 二叉搜索树中的插入操作
数据结构·c++·算法·leetcode