您的位置:首页 > 其它

[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;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: