标签:
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. 将第二半reverse
3. merge两个新链表
代码如下:
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 public void reorderList(ListNode head) { 14 if(head == null || head.next == null){ 15 return; 16 } 17 ListNode mid = findMid(head); 18 ListNode head2 = reverseList(mid.next); 19 mid.next = null; 20 mergeTwoLists(head, head2); 21 22 23 } 24 25 26 public ListNode findMid(ListNode head){ 27 ListNode fast = head.next; 28 ListNode slow = head; 29 while(fast != null && fast.next != null){ 30 slow = slow.next; 31 fast = fast.next.next; 32 } 33 return slow; 34 } 35 36 public ListNode reverseList(ListNode head){ 37 ListNode nextNode = head.next; 38 head.next = null; 39 while(nextNode != null){ 40 ListNode temp = nextNode.next; 41 nextNode.next = head; 42 head = nextNode; 43 nextNode = temp; 44 } 45 return head; 46 } 47 48 public ListNode mergeTwoLists(ListNode head1, ListNode head2){ 49 ListNode dummy = new ListNode(-1); 50 ListNode tail = dummy; 51 boolean isList1 = true; 52 while(head1 != null && head2 != null){ 53 if(isList1){ 54 tail.next = head1; 55 head1 = head1.next; 56 isList1 = false; 57 } 58 else if(!isList1){ 59 tail.next = head2; 60 head2 = head2.next; 61 isList1 = true; 62 } 63 tail=tail.next; 64 } 65 while(head1 != null){ 66 tail.next = head1; 67 head1 = head1.next; 68 tail =tail.next; 69 } 70 71 while(head2 != null){ 72 tail.next = head2; 73 head2 = head2.next; 74 tail = tail.next; 75 } 76 77 return dummy.next; 78 79 } 80 81 82 }
标签:
原文地址:http://www.cnblogs.com/incrediblechangshuo/p/4346128.html