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

题目: 链接: link解析: 代码:代码语言:javascript代码运行次数:0运行复制*** Definition for singly-linked list.* public class ListNode {* int

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

题目:

链接: link

解析:

代码:

代码语言:javascript代码运行次数:0运行复制
/**
 * 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;
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。 原始发表:2025-04-26,如有侵权请联系 cloudcommunity@tencent 删除return链表intnullpublic

发布者:admin,转转请注明出处:http://www.yc00.com/web/1747502056a4646484.html

相关推荐

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

    题目: 链接: link解析: 代码:代码语言:javascript代码运行次数:0运行复制*** Definition for singly-linked list.* public class ListNode {* int

    18小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信