zoukankan      html  css  js  c++  java
  • 20.11.13 leetcode328

    题目链接:https://leetcode-cn.com/problems/odd-even-linked-list/

    题意:给一串列表,将奇数索引的结点全部移到偶数索引结点的前面,且不得改变奇偶结点间的顺序,要求时间复杂度O(N),空间复杂度O(1)

    分析:从头到尾遍历,原先的head链表只存奇数结点,另外定义一个evenhead链表只存偶数结点,最后将evenhead接在head后面。

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode() : val(0), next(nullptr) {}
     *     ListNode(int x) : val(x), next(nullptr) {}
     *     ListNode(int x, ListNode *next) : val(x), next(next) {}
     * };
     */
    class Solution {
    public:
        ListNode* oddEvenList(ListNode* head) {
            if(head==nullptr)return head;
            ListNode* evenhead=head->next;
            ListNode* odd=head;
            ListNode* even=head->next;
            while(even!=nullptr&&even->next!=nullptr){
                odd->next=even->next;
                odd=odd->next;
                even->next=odd->next;
                even=even->next;
            }
            odd->next=evenhead;
            return head;
        }
    };
  • 相关阅读:
    视图
    触发器
    DNS
    DHCP
    SSH 详解
    apt-get
    java split
    数组指针 指针数组
    函数指针
    网络协议
  • 原文地址:https://www.cnblogs.com/qingjiuling/p/13970238.html
Copyright © 2011-2022 走看看