给定一个链表,比如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);
	}
}



阅读更多
个人分类: 笔试面试题
上一篇Socket & InetAddress的使用
下一篇给定一个数组a[N],我们希望构造数组b [N],其中b[j]=a[0]*a[1]…a[N-1] / a[j],在构造过程中,不允许使用除法
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭