题目
给定一个单链表 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 class P143 {
public void reorderList(ListNode head) {
//快慢指针找到链表的中点
if (head == null || head.next == null) {
return;
}
ListNode fast = head;
ListNode low = head;
while (fast != null && fast.next != null) {
low = low.next;
fast = fast.next;
if (fast != null) {
fast = fast.next;
}
}
//得出的两个队列head和low
ListNode p = head;
ListNode q = reverseList(low);
ListNode tmpp = null;
ListNode tmpq = null;
//将low插入head的间隙中
while (q!=null&&q.next != null) {
tmpp = p.next;
p.next = q;
tmpq = q.next;
q.next = tmpp;
p = tmpp;
q = tmpq;
}
}
private ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode pre = head;
ListNode p = head.next;
pre.next = null;
ListNode af = null;
while (p != null) {
af = p.next;
p.next = pre;
pre = p;
p = af;
}
return pre;
}
}
思路:
- 快慢指针分出相等的两端
- 想后面一段进行翻转
- 将后面的链表插入前面的链表中去