LeetCode Reorder List
2014-04-17 18:27
246 查看
[b]Problem Description[/b]
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
[b]Problem Solution[/b]
Note: 引入STL list结构来存储链表结点的值,然后通过重排规则改变结点值的顺序并存储在list中,最后再将改变后List中值存储到原linked list中,完成整个操作
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}.
[b]Problem Solution[/b]
Note: 引入STL list结构来存储链表结点的值,然后通过重排规则改变结点值的顺序并存储在list中,最后再将改变后List中值存储到原linked list中,完成整个操作
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { private: list<int> intList; public: void reorderList(ListNode *head) { if(head==NULL || head->next==NULL) return; ListNode *p=head; int listSize=0; while(p) { intList.push_back(p->val); p=p->next; listSize++; } list<int> tmpList; //setup a new list to store the target value list<int>::iterator iterBegin=intList.begin(); for(int i=0;i<listSize/2;++i) //traverse the first half of list { tmpList.push_back(*iterBegin++); //first push the begin value of list tmpList.push_back(intList.back()); //second push the last value of list intList.pop_back(); //third, pop the last value of list } if(listSize%2) //if the list size is odd, last value of list need to be pushed tmpList.push_back(intList.back()); p=head; list<int>::iterator tIter=tmpList.begin(); while(p && tIter != tmpList.end()) //traverse the list and change its value { p->val=*tIter++; p=p->next; } } };
相关文章推荐
- 【Leetcode】Reorder List
- Leetcode: Reorder List
- LeetCode Reorder List
- LeetCode之“链表”:Reorder List
- Reorder List --LeetCode
- (Leetcode 143 )Reorder List
- leetcode之Reorder List
- [leetcode][list] Reorder List
- LeetCode之 Reorder List解决思路
- LeetCode :: Reorder List
- Java for LeetCode 143 Reorder List
- 【leetcode】Reorder List
- LeetCode:Reorder List C++与Java实现
- [LeetCode] Reorder List 链表重排序
- [LeetCode 第9题] -- Reorder List
- Leetcode Reorder List
- Leetcode: Reorder List
- LeetCode:Reorder List
- 【leetcode每日一题】Reorder List
- [leetcode] Reorder List