Java怎么实现成对交换节点
更新:HHH   时间:2023-1-7


本篇内容主要讲解“Java怎么实现成对交换节点”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Java怎么实现成对交换节点”吧!

Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3
public class SwapPairs {

    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        ListNode n1 = new ListNode(3);
        ListNode n2 = new ListNode(4);

        l1.next = n1;
        n1.next = n2;


        SwapPairs sp = new SwapPairs();
        ListNode head = sp.swapPairs(l1);
        System.out.println(head.val);
        System.out.println(head.next.val);
        System.out.println(head.next.next.val);

    }

    ListNode swapPairs(ListNode head)
    {
        if(head == null || head.next == null)
            return head;
        ListNode first = head;
        ListNode last = head.next;
        first.next = swapPairs(last.next);//递归思想 很重要
        last.next = first;
        return last;
    }
}

到此,相信大家对“Java怎么实现成对交换节点”有了更深的了解,不妨来实际操作一番吧!这里是天达云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

返回云计算教程...