[Linked List]Reorder List
otal Accepted: 54991 Total Submissions: 252600 Difficulty: Medium
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes' values.
For example,
Given {1,2,3,4}, reorder it to {1,4,2,3}.
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseList(ListNode* head) { ListNode* cur = head; ListNode* newHead = NULL; ListNode* next = NULL; while(cur){ next = cur->next; cur->next = newHead; newHead = cur; cur = next; } return newHead; } void reorderList(ListNode* head) { if(head==NULL || head->next==NULL){ return; } ListNode* slow = head; ListNode* fast = head; ListNode* pre = NULL; while(fast){ pre = slow; slow = slow->next; fast->next ? fast = fast->next->next : fast = NULL; } pre->next = NULL; ListNode* head2 = reverseList(slow); ListNode* cur = head; ListNode* cur_next = NULL; ListNode* cur2 = head2; ListNode* cur2_next = NULL; while(cur2){ cur_next = cur->next; cur2_next = cur2->next; cur->next = cur2; cur2->next = cur_next; cur = cur_next; cur2 = cur2_next; } } };
写者:zengzy
出处: http://www.cnblogs.com/zengzy
标题有【转】字样的文章从别的地方转过来的,否则为个人学习笔记
 
                    
                     
                    
                 
                    
                 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号