zoukankan      html  css  js  c++  java
  • 328. Odd Even Linked List

    问题描述:

    Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.

    You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.

    Example 1:

    Input: 1->2->3->4->5->NULL
    Output: 1->3->5->2->4->NULL
    

    Example 2:

    Input: 2->1->3->5->6->4->7->NULL
    Output: 2->3->6->7->1->5->4->NULL
    

    Note:

    • The relative order inside both the even and odd groups should remain as it was in the input.
    • The first node is considered odd, the second node even and so on ...

    解题思路:

    这道题让我们把奇数位的节点连到一起,把偶数位的节点连到一起。

    所以我们可以用两个指针分别记录奇数位的起始(oddStart)和偶数位(evenStart)的起始。

    然后遍历分别给偶数位和奇数位分别链接新的节点。

    需要注意的是:

    if(temp->next)
         temp->next = temp->next->next;

    这里的判断条件,若出错会出现死循环!!!(因为最后的节点没有连到NULL)

    代码:

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* oddEvenList(ListNode* head) {
            if(!head || !head->next)
                return head;
            ListNode* oddStart = head;
            ListNode* evenStart = head->next;
            ListNode* cur = oddStart;
            ListNode* prev = cur;
            while(cur && cur->next){
                ListNode* temp = cur->next;
                cur->next = temp->next;
                if(temp->next)
                    temp->next = temp->next->next;
                prev = cur;
                cur = cur->next;
            }
            if(cur){
                cur->next = evenStart;
            }else{
                prev->next = evenStart;
            }
            return head;
        }
    };
  • 相关阅读:
    工作总结 vue 城会玩
    vue中,class、内联style绑定、computed属性
    vue-router2.0 组件之间传参及获取动态参数
    vue-router(2.0)
    在v-for中利用index来对第一项添加class(vue2.0)
    机器学习:从入门到沉迷
    探索AutoLayout的本质和解决一些问题
    软件的极简主义
    数组最大差值的最优解法(动态规划)
    项目管理--敏捷开发在项目中使用
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9216204.html
Copyright © 2011-2022 走看看