题解 | #链表的奇偶重排#

链表的奇偶重排

https://www.nowcoder.com/practice/02bf49ea45cd486daa031614f9bd6fc3

思路并没有用到链表的知识,运用到的时vector容器,哈哈哈,这个还是太好用。代码还算简单
/**
 * struct ListNode {
 *    int val;
 *    struct ListNode *next;
 *    ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @return ListNode类
     */
    ListNode* oddEvenList(ListNode* head) {
        // write code here
        vector<int>vec;
        ListNode*tmp = head;
        int n =0;
        while(tmp!=NULL)
        {
            vec.push_back(tmp->val);
            tmp =tmp->next;
            n++;
        }
        tmp = head;
        if(n%2)
        {
            for(int i =0;i<=n-1;i+=2)
            {
                tmp->val = vec[i];
                tmp=tmp->next;
            }
            for(int i =1;i<=n-2;i+=2)
            {
                tmp->val = vec[i];
                tmp= tmp->next;
            }
        }
        else{
            for(int i =0;i<=n-2;i+=2)
            {
                tmp->val = vec[i];
                tmp=tmp->next;
            }
            for(int i =1;i<=n-1;i+=2)
            {
                tmp->val = vec[i];
                tmp= tmp->next;
            }
        }
        return head; 
    }
};
全部评论

相关推荐

03-01 21:45
中北大学 golang
孤蓝长空:请你说一下为什么你用websocket而不是http,请你说一下什么是rpc,为什么用rpc,你的rpc的传输协议是JSON,xml还是什么 请你描述一下你的鉴权流程(完整的) 我问的是第二个项目,随便问的哈哈哈
开工第一帖
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务