给定一个单链表 L:L0→L1→…→Ln-1→Ln , 将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
给定链表 1->2->3->4, 重新排列为 1->4->2->3.
代码
class Solution {
public void reorderList(ListNode head
) {
double n
= 0;
if(head
==null
) return;
ListNode cnt
= head
;
while (cnt
!= null
) {
n
++;
cnt
= cnt
.next
;
}
ListNode r
= head
;
for (int i
= 0; i
< Math
.ceil(n
/ 2)-1; i
++) {
r
= r
.next
;
}
ListNode cur
= r
.next
, pre
= null
;
r
.next
=null
;
while (cur
!= null
) {
ListNode temp
= cur
.next
;
cur
.next
= pre
;
pre
= cur
;
cur
= temp
;
}
while (pre
!= null
) {
ListNode np
= pre
.next
, nh
= head
.next
;
head
.next
= pre
;
pre
.next
= nh
;
pre
= np
;
head
= nh
;
}
}
}