|
| 1 | +/** |
| 2 | + * Definition for singly-linked list. |
| 3 | + * struct ListNode { |
| 4 | + * int val; |
| 5 | + * ListNode *next; |
| 6 | + * ListNode() : val(0), next(nullptr) {} |
| 7 | + * ListNode(int x) : val(x), next(nullptr) {} |
| 8 | + * ListNode(int x, ListNode *next) : val(x), next(next) {} |
| 9 | + * }; |
| 10 | + */ |
| 11 | +class Solution { |
| 12 | +public: |
| 13 | + void reorderList(ListNode* head) { |
| 14 | + ListNode* slow = head; |
| 15 | + ListNode* fast = head; |
| 16 | + while (fast->next && fast->next->next) { |
| 17 | + slow = slow->next; |
| 18 | + fast = fast->next->next; |
| 19 | + } |
| 20 | + |
| 21 | + ListNode* curr = slow->next; |
| 22 | + slow->next = nullptr; |
| 23 | + ListNode* prev = nullptr; |
| 24 | + |
| 25 | + while (curr) { |
| 26 | + ListNode* temp = curr->next; |
| 27 | + curr->next = prev; |
| 28 | + prev = curr; |
| 29 | + curr = temp; |
| 30 | + } |
| 31 | + |
| 32 | + ListNode* first = head; |
| 33 | + ListNode* second = prev; |
| 34 | + |
| 35 | + while (second) { |
| 36 | + ListNode* temp1 = first->next; |
| 37 | + ListNode* temp2 = second->next; |
| 38 | + |
| 39 | + first->next = second; |
| 40 | + second->next = temp1; |
| 41 | + |
| 42 | + first = temp1; |
| 43 | + second = temp2; |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + // void reorderList(ListNode* head) { |
| 48 | + // ListNode* now = head; |
| 49 | + // stack<ListNode*> sta; |
| 50 | + |
| 51 | + // while(now) { |
| 52 | + // sta.push(now); |
| 53 | + // now = now->next; |
| 54 | + // } |
| 55 | + |
| 56 | + // now = head; |
| 57 | + // int n = sta.size(); |
| 58 | + // for(int i = 0; i < n / 2; i++) { |
| 59 | + // ListNode* tail = sta.top(); |
| 60 | + // sta.pop(); |
| 61 | + |
| 62 | + // tail->next = now->next; |
| 63 | + // now->next = tail; |
| 64 | + // now = tail->next; |
| 65 | + // } |
| 66 | + |
| 67 | + // now->next = nullptr; |
| 68 | + // } |
| 69 | + |
| 70 | + // void reorderList(ListNode* head) { |
| 71 | + // ListNode* now = head; |
| 72 | + // stack<ListNode*> sta; |
| 73 | + |
| 74 | + // while(now) { |
| 75 | + // sta.push(now); |
| 76 | + // now = now->next; |
| 77 | + // } |
| 78 | + |
| 79 | + // now = head; |
| 80 | + // int cnt = 0; |
| 81 | + // int node_cnt = sta.size(); |
| 82 | + // while(cnt < node_cnt / 2) { |
| 83 | + // if(cnt != node_cnt / 2 - 1) |
| 84 | + // sta.top()->next = now->next; |
| 85 | + // else { |
| 86 | + // if(node_cnt & 1) { |
| 87 | + // now->next->next = nullptr; |
| 88 | + // sta.top()->next = now->next; |
| 89 | + // } |
| 90 | + // else |
| 91 | + // sta.top()->next = nullptr; |
| 92 | + // } |
| 93 | + // now->next = sta.top(); |
| 94 | + // now = sta.top()->next; |
| 95 | + // sta.pop(); |
| 96 | + // cnt++; |
| 97 | + // } |
| 98 | + // } |
| 99 | +}; |
| 100 | + |
0 commit comments