[LeetCode 143]Reorder List

题目链接: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}. * */public class ReorderList {public class ListNode {int val;ListNode next;ListNode(int x) {val = x;next = null;}}//13 / 13 test cases passed.//Status: Accepted//Runtime: 337 ms//Submitted: 23 minutes agopublic void reorderList(ListNode head) {ListNode midNode = head;ListNode lastNode = head;//找到链表的中点while(lastNode.next != null && lastNode.next.next != null) {midNode = midNode.next;lastNode = lastNode.next.next;}lastNode = midNode.next;//断开链表midNode.next = null;//反转后半链表midNode = reverseList(lastNode);//合并链表ListNode cur = head;while( midNode != null) {ListNode node = cur.next;cur.next = midNode;midNode = midNode.next;cur = cur.next;cur.next = node;cur = cur.next;}}public ListNode reverseList(ListNode head) {ListNode preHead = new ListNode(Integer.MAX_VALUE);while(head != null) {ListNode node = preHead.next;preHead.next = head;head = head.next;preHead.next.next = node;}return preHead.next;}public static void main(String[] args) {System.out.println(Math.ceil(1.0 / 2.0));}}

,记忆的屏障,曾经心动的声音已渐渐远去。

[LeetCode 143]Reorder List

相关文章:

你感兴趣的文章:

标签云: