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

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

要求:

1、间复杂度O(1);

2、节点

class Node

{

int value;

Node next;

}

思路:把链表分为两部分前后两个部分,把后部翻转,然后把后部依次插入前部。

class Node {
	public int value;
	public Node next;

	public Node(int value, Node next) {
		this.value = value;
		this.next = next;
	}
}

public class ListNodePosition{
	public static void printList(Node head)
	{
		   while (head != null) {  
	            System.out.print(head.value+"  ");  
	            head = head.next;  
	        }  
	        System.out.println(); 
	}
	public static void ChangePosition(Node head) {
		if (head == null || head.next == null)
			return;
		Node tmp = head;
		int num = 0;
		while (tmp != null) {
			tmp = tmp.next;
			num++;
		}
		System.out.println(num);
		int n = 0;
		tmp = head;
		Node pre1=null;
		Node next1=null;
		int count;
		if(num%2!=0)count=num/2+1;
		else count=num/2;
			while (n < count) {			
				if(n==(count-1))pre1=tmp;
				tmp = tmp.next;
				n++;
				System.out.println(tmp.value);
			}
		pre1.next=null;
		printList(head);
		printList(tmp);
		Node pre =null;
		Node next=null;
		while(tmp!=null)
		{
			next=tmp.next;
			tmp.next=pre;
			pre=tmp;
			tmp= next;
		}
		tmp=pre;
		next=null;
		printList(pre);
        System.out.println(n);
        pre1=head;
		for(int i=0;i<num/2;i++)
		{
			next1=pre1.next;
			next=tmp.next;
			pre1.next=tmp;
			tmp.next=next1;
			pre1=next1;
			tmp=next;
			
		}
		printList(head);	
	}
	
	public static void main(String[] argv) {
		Node node1 = new Node(0, null);
		Node node2 = new Node(1, null);
		Node node3 = new Node(2, null);
		Node node4 = new Node(3, null);
		Node node5 = new Node(4, null);
		Node node6 = new Node(5, null);
		//Node node7 = new Node(6, null);
		node1.next = node2;
		node2.next = node3;
		node3.next = node4;
		node4.next = node5;
		node5.next = node6;
		//node6.next = node7;
		ChangePosition(node1);
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值