nikunjsoni

143

Mar 19th, 2021
58
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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.         if(!head->next) return;
  15.         ListNode *slow, *fast;
  16.         slow = fast = head;
  17.         // Find middle of list.
  18.         while(fast->next && fast->next->next){
  19.             slow = slow->next;
  20.             fast =fast->next->next;
  21.         }
  22.        
  23.         // Reverse list after middle.
  24.         fast = head;
  25.         while(fast->next){
  26.             fast = fast->next;
  27.         }
  28.         ListNode *start, *tmp;
  29.         start = slow->next;
  30.         while(start != fast){
  31.             tmp = start;
  32.             start = start->next;
  33.             tmp->next = fast->next;
  34.             fast->next = tmp;
  35.         }
  36.         slow->next = NULL;
  37.        
  38.         //Do zigzag ordering.
  39.         slow = head;
  40.         fast = start;
  41.         ListNode *dummy = new ListNode(0);
  42.         head = dummy->next;
  43.         while(slow || fast){
  44.             if(slow) dummy->next = slow, slow = slow->next, dummy = dummy->next;
  45.             if(fast) dummy->next = fast, fast = fast->next, dummy = dummy->next;
  46.         }
  47.     }
  48. };
RAW Paste Data