将给定的单链表:
重新排序为:
要求使用原地算法,不能只改变节点内部的值,需要对实际的节点进行交换。
数据范围:链表长度 ,链表中每个节点的值满足
重新排序为:
要求使用原地算法,不能只改变节点内部的值,需要对实际的节点进行交换。
数据范围:链表长度 ,链表中每个节点的值满足
要求:空间复杂度 并在链表上进行操作而不新建链表,时间复杂度
进阶:空间复杂度 , 时间复杂度
{1,2,3,4}
{1,4,2,3}
给定head链表1->2->3->4, 重新排列为 1->4->2->3,会取head链表里面的值打印输出 1
{1,2,3,4,5}
{1,5,2,4,3}
给定head链表1->2->3->4->5, 重新排列为 1->5>2->4->3,会取head链表里面的值打印输出
{}
{}
/* * function ListNode(x){ * this.val = x; * this.next = null; * } */ /** * * @param head ListNode类 * @return void */ function reorderList( head ) { if (!head) { return head; } let cur = head; let pre = null; while (cur) { cur.pre = pre; pre = cur; cur = cur.next; } let tail = pre; cur = head; while (cur !== tail && cur.next !== tail) { let next = cur.next let pre = tail.pre; cur.next = tail; tail.next = next; cur = next; tail = pre; } tail.next = null; return head; } module.exports = { reorderList : reorderList };
class Reorder { static splitList(head) { let slow = head, fast = head; while (fast && fast.next) { slow = slow.next; fast = fast.next.next; } let list1 = head; let list2 = slow.next; slow.next = null; return [list1, list2]; } static reverseList(root) { let prev = null; while (root) { const next = root.next; root.next= prev; prev = root; root = next; } return prev; } static insertMerge(list1, list2) { const head = list1; list2 = Reorder.reverseList(list2); while (list2) { const node = list2; list2 = list2.next; node.next = list1.next; list1.next = node; list1= node.next; } return head; } } /** * * @param head ListNode类 * @return void */ function reorderList( head ) { if (!head || !head.next || !head.next.next) return head; const [list1, list2] = Reorder.splitList(head); return Reorder.insertMerge(list1, list2); }
function reorderList( head ) { // write code here if (head === null || head.next === null) return head let slow = head let fast = head while (slow && slow.next) { slow.next.pre = slow //变成双向链表 slow = slow.next } while (slow !== fast && slow.pre !== fast) { let next = fast.next fast.next = slow slow = slow.pre fast.next.next = next fast = next } slow.next = null return head }
/** * * @param head ListNode类 * @return void */ function reorderList( head ) { //思路,先找到链表的中间节点,然后将中间节点后续的节点逆序,然后将逆序的节点按要求插入前一半链表中 //利用快慢指针找中间节点,slow后边的都需要反序 if(head==null||head.next==null){ return ; } var slow=head; var fast=head; while(fast.next!=null&&fast.next.next!=null){ slow=slow.next; fast=fast.next.next; // console.log(slow.val) } //反序 var pre=null; var cur=slow.next; var last=cur.next; while(cur!=null){ cur.next=pre; pre=cur; cur=last; if(last!=null){ last=last.next; } } slow.next=null; //重新构建 var p=head; var p0=p.next; var q=pre; var q0=q.next; while(q!=null){ p.next=q; q.next=p0; p=p0; if(p0!=null){ p0=p0.next; } q=q0; if(q0!=null){ q0=q0.next; } } p=head; while(p!=null){ console.log(p.val); p=p.next; } return head; } module.exports = { reorderList : reorderList };