(java)链表的转换

给定一个链表,比如L1--->L2---->L3---->................----->Ln,把链表调整为L1---->Ln----->L2----->Ln-1------>L3------>Ln-3...........

要求:

1、间复杂度O(1);

思路:将后一半元素逆转之后,就可以按照后一半逆转之后的顺序插入到前一半链表中。

代码如下:

import java.util.*;

public class Main{
    public static void main(String[]args){
    	Node1 n1=new Node1(1);
    	Node1 n2=new Node1(2);
    	Node1 n3=new Node1(3);
    	Node1 n4=new Node1(4);
    	Node1 n5=new Node1(5);
    	n1.next=n2;
    	n2.next=n3;
    	n3.next=n4;
    	n4.next=n5;
    	Node1 s=n1;
    	System.out.print("原始链表为:");
    	while(s!=null){
    		if(s.next!=null)
    			System.out.print(s.val+"->");
    		else
    			System.out.print(s.val);
    		s=s.next;
    	}
    	System.out.println();
    	n1=Change(n1);
    	s=n1;
    	System.out.print("转换后的链表为:");
    	while(s!=null){
    		if(s.next!=null)
    			System.out.print(s.val+"->");
    		else
    			System.out.print(s.val);
    		s=s.next;
    	}
    }
    public static Node1 Change(Node1 head){
    	int count=0;
    	Node1 t=head;
    	while(t!=null){
    		count++;
    		t=t.next;
    	}
        t=head;
        for(int i=0;i<count/2;i++){
        	t=t.next;
        }
        //首先翻转后一半的结点
        t=Reverse(t);
        //将后一半插入到前一半的链表中
        Node1 r=head;
        for(int i=0;i<count/2;i++){
        	Node1 temp=t.next;
        	Node1 temp2=r.next;
        	t.next=r.next;
        	r.next=t;
        	t=temp;
        	r=temp2;
        }
        return head;
    }
    public static Node1 Reverse(Node1 t){
    	if(t==null){
    		return null;
    	}
    	Node1 p=t;
    	Node1 q=t.next;
    	t.next=null;
    	while(q!=null){
    		Node1 r=q.next;
    		q.next=p;
    		p=q;
    		q=r;
    	}
    	return p;
    }
}
class Node1{
	int val;
	Node1 next;
	public Node1(int v){
		this.val=v;
		this.next=null;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值