您的位置:首页 > 其它

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

2013-10-03 11:32 369 查看
给定一个链表,比如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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐