您好,欢迎来到花图问答。
搜索
您的当前位置:首页LeetCode每日一题:swap nodes in pairs

LeetCode每日一题:swap nodes in pairs

来源:花图问答

问题描述

Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given1->2->3->4, you should return the list as2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

问题分析

考察的是链表节点的交换,没什么难度。

代码实现

public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode preHead = new ListNode(0);
        preHead.next = head;
        ListNode cur = preHead;
        while (cur.next != null && cur.next.next != null) {
            cur.next = swapListNode(cur.next, cur.next.next);
            cur = cur.next.next;
        }
        return preHead.next;
    }

    private ListNode swapListNode(ListNode node1, ListNode node2) {
        node1.next = node2.next;
        node2.next = node1;
        return node2;
    }

Copyright © 2019- huatuowenda.com 版权所有 湘ICP备2023022495号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务