首页 > 代码库 > Reorder List

Reorder List

 1 #define NULL 0 2  3 class Solution { 4 public: 5     void reorderList(ListNode *head) { 6         stack<ListNode*> s; 7         ListNode* ptr1,*ptr2,*tmp; 8         if(head != NULL && head->next != NULL && head->next->next != NULL) 9         {10            ptr1 = head;11            ptr2 = head;12            while(ptr2->next != NULL && ptr2->next->next != NULL)13            {14                ptr1 = ptr1->next;15                ptr2 = ptr2->next->next;16            }17            tmp = ptr1;18            ptr1 = ptr1->next;19            tmp->next = NULL;20            ptr2 = head;21            while(ptr1 != NULL)22            {23                s.push(ptr1);24                ptr1 = ptr1->next;25            }26            while(s.size())27            {28                tmp = ptr2->next;29                ListNode* top;30                top = s.top();31                s.pop();32                ptr2->next = top;33                top->next = tmp;34                ptr2 = ptr2->next->next;35            }36         }37 38     }39 };