算法练习:NC2_中等
题目:
将给定的单链表 L: L_0→L_1→…→L_n−1→L_n
重新排序为: L_0→L_n→L_1→L_n−1→L_2→L_n−2→…
要求使用原地算法,不能改变节点内部的值,需要对实际的节点进行交换。
例如:
对于给定的单链表{10,20,30,40},将其重新排序为{10,40,20,30}.
解答
public class Solution {
public void reorderList(ListNode head) {
if(head == null || head.next == null)
return;
// 1.快慢指针找到中间节点
ListNode fast = head; //快指针,当前节点+2
ListNode slow = head; //慢指针,当前节点+1
while(fast.next != null && fast.next.next != null){
fast = fast.next.next; //最后fast为尾节点
slow = slow.next; //最后slow为中间节点
}
// 2.拆分链表,并反转中间节点之后的链表
ListNode after = slow.next; //第二条链的头节点,即中间节点后节点
ListNode pre = null; //存储目标节点的前节点
ListNode temp = null; //临时变量,存储后节点
slow.next = null; //断链
while(after != null){
temp = after.next; //存储下一个节点
after.next = pre; //反转链表,将next指向前节点
pre = after; //前节点来到目标节点
after = temp; //去下一个节点
}
// 3.合并两个链表
ListNode ftemp = null; //存储合并链的当前节点的直接后继
ListNode aftemp = null; //存储二链的当前节点的直接前驱
ListNode first = head; //合并链的头节点
after = pre; //第二条链反转后的头节点
while(first != null && after != null){
ftemp = first.next;
aftemp = after.next;
first.next = after; //合并链指向二链的节点
first = ftemp;
after.next = first; //二链节点指向合并链
after = aftemp;
}
}
}
个人整理的笔记,仅供学习使用,有问题麻烦指正。
题目及解答思路均来源于:牛客网