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

题目:

链接: 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