Reorder List

Given a singly linked list L: L0 → L1 → … → Ln-1 → Ln

reorder it to: L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → …

Example

Given 1->2->3->4->null, reorder it to 1->4->2->3->null.

 1 /**
 2  * Definition of ListNode
 3  * class ListNode {
 4  * public:
 5  *     int val;
 6  *     ListNode *next;
 7  *     ListNode(int val) {
 8  *         this->val = val;
 9  *         this->next = NULL;
10  *     }
11  * }
12  */
13 class Solution {
14 public:
15     /**
16      * @param head: The first node of linked list.
17      * @return: void
18      */
19     void reorderList(ListNode *head) {
20         if (head == NULL) {
21             return;
22         }
23         ListNode *head2 = findMiddle(head);
24         ListNode *tail2 = head2->next;
25         tail2 = reverse(tail2);
26         head2->next = NULL;
27         ListNode *tail1 = head;
28         
29         int count = 1;
30         ListNode *dummy = new ListNode(0);
31         ListNode *tail = dummy;
32         while (tail1 != NULL && tail2 != NULL) {
33             if (count % 2 != 0) {
34                 tail->next = tail1;
35                 tail1 = tail1->next;
36                 tail = tail->next;
37                 ++count;
38             } else {
39                 tail->next = tail2;
40                 tail2 = tail2->next;
41                 tail = tail->next;
42                 ++count;
43             }
44         }
45         if (tail1 != NULL) {
46             tail->next = tail1;
47         } else {
48             tail->next = tail2;
49         }
50     }
51 
52     ListNode* reverse(ListNode *head) {
53         if (head == NULL || head->next == NULL) {
54             return head;
55         }
56         ListNode *newHead = NULL;
57         while (head) {
58             ListNode *temp = head->next;
59             head->next = newHead;
60             newHead =  head;
61             head = temp;
62         }
63         return newHead;
64     }
65 
66     ListNode* findMiddle(ListNode *head) {
67         if (head == NULL || head->next == NULL) {
68             return head;
69         }
70         ListNode *slow = head;
71         ListNode *fast = head->next;
72         while (fast != NULL && fast->next != NULL) {
73             slow = slow->next;
74             fast = fast->next->next;
75         }
76         return slow;
77     }
78 
79 };

 

posted @ 2016-04-21 15:11  YuriFLAG  阅读(137)  评论(0)    收藏  举报