欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode ---- 24、两两交换链表中的节点

程序员文章站 2022-06-07 10:46:25
...

题目链接

思路:

因为是两两交换,所以需要注意当只剩下一个节点的时候,就不需要交换了。

下面开始使用例子来讲解代码:

原链表如下:

LeetCode ---- 24、两两交换链表中的节点

三个指针,cur记录当前节点,curNext记录cur的next节点,curNextNext记录curNext的next节点

LeetCode ---- 24、两两交换链表中的节点

开始翻转next指针指向,

前两个翻转:

LeetCode ---- 24、两两交换链表中的节点

第3和第4个翻转:

LeetCode ---- 24、两两交换链表中的节点

最后拉直链表:

LeetCode ---- 24、两两交换链表中的节点

    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }

        ListNode cur = head;
        ListNode curNext = cur.next;
        head = curNext;
        while (cur != null && curNext != null) {
            ListNode curNextNext = curNext.next;
            curNext.next = cur;
            ListNode tmp = cur;
            cur = curNextNext;
            if (curNextNext != null && curNextNext.next != null) {
                tmp.next = curNextNext.next;
                curNext = curNextNext.next;
            } else {
                tmp.next = curNextNext;
                curNext = null;
            }
        }
        return head;
    }
    class ListNode {
        int val;
        ListNode next;
        ListNode(int x) { val = x; }
    }

 

相关标签: LeetCode