题目
给定一个链表L: L0→L1→…→Ln-1→Ln,
重新排列后为:L0→Ln→L1→Ln-1→L2→Ln-2→…
必须在不改变节点值的情况下进行原地操作。
样例
给出链表 1->2->3->4->null,重新排列后为1->4->2->3->null。
思路
此处使用一个双向链表,在原有的链表上进行操作。依次循环只需把 n 处的节点放到 1 的位置,n-1 处的节点放到 2 的位置,直到输出符合条件的链表。
public class LinkNote {
public static Note updateLinkNote(Note head, Note tail, int length) {
if(length <= 0 || null == head){
return null;
}else if(null == tail && null != head){
return head;
}
//循环 length/2 次,每次把尾节点放到对应的节点的后面,定义当前要操作的节点
Note current = null;
int num = length/2;
//链表长度为偶数的时候,循环次数 -1
if(length%2==0 ){
num = num - 1;
}
current = head;
for (int i=0; i<num; i++){
//把当前节点的 next 节点保存起来
Note next = current.next;
//保存尾节点的前置节点
Note prev = null;
if(null != tail){
prev = tail.prev;
}
//当前节点的 next 节点是尾节点
current.next = tail;
//尾节点 tail 的 next 节点为原来的 next 节点
tail.next = next;
//尾节点 tail 的前置节点为当前节点
tail.prev = current;
//下一个要操作的当前节点为原来的 next 节点
current = next;
//把原尾节点的前置节点设置为新的尾节点
tail = prev;
}
//设置尾节点的 next 节点为空
tail.next = null;
return head;
}
public class Note {
Note prev;
Note next;
int value;
public Note(int vlaue){
this.value = vlaue;
}
}
}