leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0143.cpp (980B)


      1 class Solution {
      2     ListNode *reverseList(ListNode *head) {
      3         ListNode *p, *q, *r;
      4 
      5         p = head, q = nullptr;
      6         while (p) {
      7             r = q;
      8             q = p;
      9             p = p->next;
     10             q->next = r;
     11         }
     12 
     13         return q;
     14     }
     15 
     16     ListNode *bmiddleNode(ListNode *head) {
     17         ListNode *fast, *slow;
     18         fast = slow = head;
     19         while (fast->next && fast->next->next) {
     20             fast = fast->next->next;
     21             slow = slow->next;
     22         }
     23 
     24         return slow;
     25     }
     26 
     27   public:
     28     void reorderList(ListNode *head) {
     29         ListNode *bmid = bmiddleNode(head);
     30         ListNode *rev = reverseList(bmid->next);
     31         bmid->next = nullptr;
     32 
     33         ListNode top, *tmp = &top, *a, *b, *an;
     34         for (a = head, b = rev; b; b = b->next, a = an) {
     35             an = a->next;
     36             tmp = tmp->next = a;
     37             tmp = tmp->next = b;
     38         }
     39         if (a) tmp = tmp->next = a;
     40         tmp->next = nullptr;
     41     }
     42 };