Reorder List [LeetCode]

Given a singly linked list LL0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-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}.

Solution: make sure the last element points to NULL in the new list;

 1     void reorderList(ListNode *head) {

 2         vector<ListNode * > nodes;

 3         ListNode * current = head;

 4         while(current != NULL) {

 5             nodes.push_back(current);

 6             current = current->next;

 7         }

 8         for(int i = 0; i < nodes.size() / 2; i ++){

 9             int next = nodes.size() - 1 - i;

10             if(i < next){

11                 ListNode * tmp = nodes[i]->next;

12                 nodes[i]->next = nodes[next];

13                 nodes[next]->next = tmp;

14             }

15         }

16         if(nodes.size() > 0)

17             nodes[nodes.size() / 2]->next = NULL;

18     }

 

 1     void reorderList(ListNode *head) {

 2         vector<ListNode * > nodes;

 3         ListNode * current = head;

 4         while(current != NULL) {

 5             nodes.push_back(current);

 6             current = current->next;

 7         }

 8         for(int i = 0; i < nodes.size() / 2; i ++){

 9             if(i < nodes.size() - 1 - i){

10                 nodes[i]->next = nodes[nodes.size() - 1 - i];

11                 if(i + 1 < nodes.size() - 1 - i)

12                     nodes[nodes.size() - 1 - i]->next = nodes[i + 1];

13                 else

14                     nodes[nodes.size() - 1 - i]->next = NULL;

15             }

16         }

17         if(nodes.size() % 2 == 1)

18             nodes[nodes.size() / 2]->next = NULL;

19     }

 

你可能感兴趣的:(LeetCode)