【leetcode】Reorder List
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes' values.
For example,
Given {1,2,3,4}
, reorder it to {1,4,2,3}
.
题解:看起来最后变换得到的链表顺序很奇怪,起始很简单,就是把链表从中间折断,后半部分反转后和前半部分做归并即可。不过这个归并不是归并排序每次从两个链表中取较小的值,而是两个链表相互交错即可。
例如1->2->3->4,从中间折断得到两个链表1->2和3->4,后面一个链表反转得到4->3,然后和第一个链表交错归并得到1->3->2->4;
再例如1->2->3->4->5,从中间折断得到两个链表1->2->3和4->5,后一个链表反转得到5->4,和第一个链表交错归并得到1->4->2->5->3;
代码如下:
1 /** 2 * Definition for singly-linked list. 3 * class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 private ListNode reverse(ListNode head){ 14 ListNode newHead = null; 15 while(head != null){ 16 ListNode temp = head.next; 17 head.next = newHead; 18 newHead = head; 19 head = temp; 20 } 21 return newHead; 22 } 23 24 private void newMerge(ListNode head1,ListNode head2){ 25 ListNode newHead = new ListNode(0); 26 27 while(head1 != null && head2 != null){ 28 newHead.next = head1; 29 head1 = head1.next; 30 newHead = newHead.next; 31 newHead.next = head2; 32 head2 = head2.next; 33 newHead = newHead.next; 34 } 35 if(head1 != null) 36 newHead.next = head1; 37 if(head2 != null) 38 newHead.next = head2; 39 } 40 private ListNode findMiddle(ListNode head){ 41 ListNode slow = head; 42 ListNode fast = head.next; 43 while(fast != null && fast.next != null) 44 { 45 slow = slow.next; 46 fast = fast.next.next; 47 } 48 return slow; 49 } 50 public void reorderList(ListNode head) { 51 if(head == null || head.next == null) 52 return; 53 54 ListNode mid = findMiddle(head); 55 ListNode tail = reverse(mid.next); 56 mid.next = null; 57 58 newMerge(head, tail); 59 } 60 }
分类:
leetcode刷题总结
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了