重排链表
给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
给定链表 1->2->3->4, 重新排列为 1->4->2->3.
示例 2:
给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.
思路+代码+注释:
public void reorderList(ListNode head) {
/*
思路:使用start记录开始交换的节点,last记录当前最后的节点,pre记录最后一个节点的前一个节点
从start节点开始,如果start.next.next!=null说明需要重排,否则不需要直接退出循环。然后从start.next.next开始寻找最后一个节点,然后将最后一个
节点移动到start节点后面,start.next.next成为新的start节点
*/
ListNode start=head;
ListNode pre=null;
ListNode last=null;
ListNode end=null;
ListNode a=null;
while (start!=null)
{
if (start.next!=null && start.next.next!=null)
{
a=start.next;
while (a!=null)
{
if (a.next!=null)
{
pre=a;
}
else
{
end=a;
}
a=a.next;
}
pre.next=null;
end.next=start.next;
start.next=end;
start=start.next.next;
}else {
break;
}
}
}