LeetCode143之ReorderList的Java题解
来源:互联网 发布:网络用语开车什么意思 编辑:程序博客网 时间:2024/06/07 00:38
题目:
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,节点插入
代码如下:
public static void reorderList(ListNode head) {if(head!=null&&head.next!=null){ListNode middle=getMideeldofList(head);ListNode next=middle.next;middle.next=null;ListNode backNode=ReverseList(next);ListNode cur=head,cur1=backNode;ListNode next1=null,next2=null;while(cur!=null&&cur1!=null){ next1=cur.next; next2=cur1.next; cur.next=cur1; cur1.next=next1; cur=next1; cur1=next2;}} }public static ListNode getMideeldofList(ListNode head){if(head==null||head.next==null)return head;ListNode slow=head,fast=head;while(fast!=null&&fast.next!=null){fast=fast.next.next;slow=slow.next;}return slow;}public static ListNode ReverseList(ListNode head){if(head==null||head.next==null)return head;ListNode fakeNode=new ListNode(-1);fakeNode.next=head;ListNode pre=fakeNode,cur=head.next,firstNode=head;while(cur!=null){ListNode next=cur.next;cur.next=pre.next;pre.next=cur;cur=next;}firstNode.next=null;return fakeNode.next;}
第二种解法:
听过一句话,软件解决起来很复杂的问题有时候用硬件能够很轻松地解决,同样需要用复杂的代码实现的功能有时候通过选择恰当的数据结构能够很方便解决。
在这题中,我们可以通过把链表的节点放入一个栈中,通过这么一个步骤可以实现上面寻找中间节点和链表转置两个功能,接着就只需要进行节点插入的操作了。
代码:
public static void reorderList2(ListNode head) { if(head==null||head.next==null) return; Stack<ListNode> stack=new Stack<>(); ListNode cur=head; while(cur!=null) { stack.push(cur); cur=cur.next; } int count=stack.size()/2; cur=head; ListNode nextNode=null,tempNode=null; while(count>0) { tempNode=stack.pop(); nextNode=cur.next; cur.next=tempNode; tempNode.next=nextNode; cur=nextNode; count--; } if(nextNode!=null) { nextNode.next=null; } }
0 0
- LeetCode143之ReorderList的Java题解
- AJAXControlToolKit的ReorderList控件
- Reorderlist
- ReorderList
- ReorderList的Edit如何使用
- LeetCode2之AddTwoNumbers的java题解
- LeetCode86之PartionList的java题解
- LeetCode24之SwapNodesInPairs的Java 题解
- LeetCode92之Reverse Linked ListII的 Java题解
- LeetCode83之Remove Duplicates from Sorted List的Java题解
- LeetCode 148之Sort List的java题解
- LeetCode143 Reorder List
- LeetCode143—Reorder List
- LeetCode143. Reorder List
- leetcode143. Reorder List
- leetcode143~Reorder List
- leetcode143. Reorder List
- 刷题——ReorderList
- mysql分区
- 使用字段的值作为数组下标
- Go语言标准库Json的使用.
- 待解决问题集锦
- 【contentprovider系列5】修改联系人信息
- LeetCode143之ReorderList的Java题解
- 第8周项目1(2)实现复数类中的运算符重载(友元函数)
- WebRTC代码走读(六):视频发送流程
- Android数据存储(2)——SharedPreferences
- 关于matlab中的手写字体识别 的mat文件
- google-hack相关的python脚本
- Linux应用程序之信号量
- linux命令学习笔记
- 【VR】Leap Motion 官方脚本手册翻译之---HandController(手型控制器)