首页 > 代码库 > LeetCode解题报告:Reorder List
LeetCode解题报告: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}
.
思路:
1.利用快慢两个指针将链表一分为二;
2.针对第二个子链表求倒序;
3.利用merge思想将两个子链表合并。
代码:
1 public class ReorderSingleList { 2 /** 3 * Definition for singly-linked list. class ListNode { int val; ListNode 4 * next; ListNode(int x) { val = x; next = null; } } 5 */ 6 public void reorderList(ListNode head) { 7 if (head == null || (head.next == null)) { 8 return; 9 }10 // fast and slow point find the mid position.11 ListNode fast = head;12 ListNode slow = head;13 while ((fast != null) && (fast.next != null)) {14 fast = fast.next.next;15 slow = slow.next;16 }17 18 // reverse the last second list.19 ListNode headnode = new ListNode(-1);20 headnode.next = slow;21 ListNode temp = headnode.next;22 while (temp.next != null) {23 ListNode insert = temp.next;24 ListNode currNext = insert.next;25 insert.next = headnode.next;26 headnode.next = insert;27 temp.next = currNext;28 }29 30 // merge insert31 ListNode firstcur = head;32 ListNode secondcur = headnode.next;33 while (firstcur != slow && (secondcur != slow)) {// at first,I make a mistake in here;34 ListNode firstnex = firstcur.next;35 ListNode secondnex = secondcur.next;36 firstcur.next = secondcur;37 secondcur.next = firstnex;38 firstcur = firstnex;39 secondcur = secondnex;40 }41 }42 43 public static void main(String[] args) {44 ListNode t5 = new ListNode(5);45 ListNode t4 = new ListNode(4, t5);46 ListNode t3 = new ListNode(3, t4);47 ListNode t2 = new ListNode(2, t3);48 ListNode t1 = new ListNode(1, t2);49 new ReorderSingleList().reorderList(t1);50 System.out.println(t1);51 }52 53 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。