[程序员代码面试指南]链表问题-按照左右半区的方式重新组合单链表

题意

把链表分成左右半区,奇数个节点则右半区长一点,重新交叉排列成链表,如下例:
1,2,3,4,5,# =>1,3,2,4,5,#
1,2,3,4,#=>1,3,2,4,#

题解

找到分割点,拆开再合并。

代码

public class Main {
    public static void main(String args[]) {
        //test
        Node n1=new Node(1);
        Node n2=new Node(2);
        Node n3=new Node(3);
        Node n4=new Node(4);
        n1.next=n2;
        n2.next=n3;
        n3.next=n4;
        Node head=n1;
        
        relocate(head);
        
        //test
        Node pNode=head;
        while(pNode!=null) {
            System.out.println(pNode.val);
            pNode=pNode.next;
        }
    }
    
    public static void relocate(Node head) {
        if(head!=null&&head.next!=null&&head.next.next!=null) {//至少三个节点
            Node fast=head;//
            Node slow=head;
            while(fast.next!=null&&fast.next.next!=null) {//
                fast=fast.next.next;
                slow=slow.next;
            }
            Node l=head;
            Node r=slow.next;
            slow.next=null;
            Node lTemp=null;
            Node rTemp=null;
            while(r!=null) {
                lTemp=l.next;
                l.next=r;
                l=lTemp;
                
                rTemp=r.next;
                r.next=l;
                r=rTemp;
            }
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/coding-gaga/p/10961555.html
今日推荐