reorder-list

来源:互联网 发布:sql cast函数有什么用 编辑:程序博客网 时间:2024/06/07 06:14

题目描述


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}.

--------------------------------------------------------------------------------------------------------------------------------

代码

 语言:C++ 运行时间: <1 ms 占用内存:9740K 状态:答案正确
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
classSolution {
public:
    voidreorderList(ListNode *head) {
        if(!head || !head->next) return;
        vector<int> v;
        ListNode* p = head;
        while(p){
            v.push_back(p->val);
            p = p->next;
        }
        p = head;
        inti = 0,j = v.size()-1,index = 0;
        while(i<=j){
            if(index%2==0){
                p->val = v[i++];
            }else{
                p->val = v[j--];
            }
            p = p->next;
            ++index;
        }
    }
};
    添加笔记


0 0
原创粉丝点击