🌕 24. 两两交换链表中的节点

吞佛童子2022年6月9日
  • algorithm
  • list
小于 1 分钟

🌕 24. 两两交换链表中的节点

难度: 🌕

问题描述

img_5.png


解法

/**
 * 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 pre = new ListNode(-1);
        pre.next = head;
        ListNode res = pre;
        ListNode cur = head;
        ListNode next = cur.next;
        ListNode fur = next.next;
        // 循环
        while(next != null) {
            ListNode tmp;
            pre.next = next;
            next.next = cur;
            cur.next = fur;
            // 终止条件判断
            if(fur == null) {
                break;
            } else {
                tmp = fur.next;
            }
            // 移位
            pre = cur;
            cur = fur;
            next = tmp;
            if(next == null) {
                break;
            } else {
                fur = next.next;
            }
        }
        return res.next;
    }

    private void test(ListNode pre) {
        ListNode cur = pre;
        System.out.println();
        while(cur != null) {
            System.out.print(cur.val + " -> ");
            cur = cur.next;
        }
    }
}

输出

img_8.png

上次编辑于: 2022/6/20 下午8:24:47
贡献者: liuxianzhishou