Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Definition for singly-linked list.
- * struct ListNode {
- * int val;
- * ListNode *next;
- * ListNode() : val(0), next(nullptr) {}
- * ListNode(int x) : val(x), next(nullptr) {}
- * ListNode(int x, ListNode *next) : val(x), next(next) {}
- * };
- */
- class Solution {
- public:
- void reorderList(ListNode* head) {
- if(!head->next) return;
- ListNode *slow, *fast;
- slow = fast = head;
- // Find middle of list.
- while(fast->next && fast->next->next){
- slow = slow->next;
- fast =fast->next->next;
- }
- // Reverse list after middle.
- fast = head;
- while(fast->next){
- fast = fast->next;
- }
- ListNode *start, *tmp;
- start = slow->next;
- while(start != fast){
- tmp = start;
- start = start->next;
- tmp->next = fast->next;
- fast->next = tmp;
- }
- slow->next = NULL;
- //Do zigzag ordering.
- slow = head;
- fast = start;
- ListNode *dummy = new ListNode(0);
- head = dummy->next;
- while(slow || fast){
- if(slow) dummy->next = slow, slow = slow->next, dummy = dummy->next;
- if(fast) dummy->next = fast, fast = fast->next, dummy = dummy->next;
- }
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment