您好,欢迎来到伴沃教育。
搜索
您的当前位置:首页24. Swap Nodes in Pairs

24. Swap Nodes in Pairs

来源:伴沃教育

思路: 循环修改 next 即可,一次 AC

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode current=head,next,nextnext;
        ListNode result=new ListNode(-1);
        ListNode pre=result;
        result.next = head;
        while(current!=null&&(next=current.next)!=null){
            nextnext = next.next;
            pre.next=next;
            next.next=current;
            current.next=nextnext;
            pre=current;
            current = nextnext;
        }
        return result.next;
    }
}

Copyright © 2019- bangwoyixia.com 版权所有 湘ICP备2023022004号-2

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

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