[LeetCode 第9题] -- Reorder List
2014-12-10 21:18
316 查看
题目链接: Reorder List
题目意思: 给的一个链表,要求对链表重新排序。
例如L0->L1->L2.....->Ln,要求重新排序变成L0->Ln-1->L1->Ln-2->L2....
代码:
/**
* 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);
};
void Solution::reorderList(ListNode *head) {
if (NULL == head) {
return;
}
int listCount = 0;
ListNode* tmpHead = head;
vector<int> listVal;
while (tmpHead != NULL) {
listVal.push_back(tmpHead->val);
tmpHead = tmpHead->next;
listCount++;
}
tmpHead = head;
int startToEnd = 0;
int endToStart = listCount-1;
while (tmpHead != NULL) {
tmpHead->val = listVal[startToEnd++];
tmpHead = tmpHead->next;
if (tmpHead != NULL) {
tmpHead->val = listVal[endToStart--];
tmpHead = tmpHead->next;
}
}
}
题目意思: 给的一个链表,要求对链表重新排序。
例如L0->L1->L2.....->Ln,要求重新排序变成L0->Ln-1->L1->Ln-2->L2....
代码:
/**
* 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);
};
void Solution::reorderList(ListNode *head) {
if (NULL == head) {
return;
}
int listCount = 0;
ListNode* tmpHead = head;
vector<int> listVal;
while (tmpHead != NULL) {
listVal.push_back(tmpHead->val);
tmpHead = tmpHead->next;
listCount++;
}
tmpHead = head;
int startToEnd = 0;
int endToStart = listCount-1;
while (tmpHead != NULL) {
tmpHead->val = listVal[startToEnd++];
tmpHead = tmpHead->next;
if (tmpHead != NULL) {
tmpHead->val = listVal[endToStart--];
tmpHead = tmpHead->next;
}
}
}
相关文章推荐
- LeetCode Reorder List
- Leetcode-Reorder List
- [Leetcode 143, Medium] Reorder List
- leetcode 之 Reorder List
- Leetcode:Reorder List 单链表重排序
- leetcode题目4:Reorder List
- LeetCode Reorder List
- Reorder List (leetcode)
- [LeetCode]143 Reorder List
- [LeetCode]Reorder List
- [LeetCode]Reorder List
- LeetCode_Reorder List
- 【LeetCode】Reorder List 解题报告
- [LeetCode] Reorder List
- Reorder List LeetCode
- leetcode-m-Reorder List
- LeetCode Reorder List
- LeetCode No.143 Reorder List
- Leetcode NO.143 Reorder List
- Leetcode154: Reorder List