Leetcode #143 in cpp
2016-06-26 06:31
567 查看
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
Solution:
Use a deque to link front and back.
Code:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void reorderList(ListNode* head) {
if(!head||!head->next) return;
deque<ListNode*> queue;
ListNode *cur = head->next;
while(cur){
queue.push_back(cur);
cur = cur->next;
}
cur = head;
while(!queue.empty()){
cur->next = queue.back();
queue.pop_back();
cur = cur->next;
if(queue.empty()) break;
cur->next = queue.front();
queue.pop_front();
cur = cur->next;
}
cur->next = NULL;
return;
}
};
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}.
Solution:
Use a deque to link front and back.
Code:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void reorderList(ListNode* head) {
if(!head||!head->next) return;
deque<ListNode*> queue;
ListNode *cur = head->next;
while(cur){
queue.push_back(cur);
cur = cur->next;
}
cur = head;
while(!queue.empty()){
cur->next = queue.back();
queue.pop_back();
cur = cur->next;
if(queue.empty()) break;
cur->next = queue.front();
queue.pop_front();
cur = cur->next;
}
cur->next = NULL;
return;
}
};
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- C++中const用法总结
- CPP 虚函数、虚函数表及虚拟继承(转)
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- Deploying Control Plane Policing
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解