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;
        }
    };
  • 相关阅读:
    count(1)、count(*)与count(列名)的执行区别
    解析Json字符串中的指定的值
    消息队列的好处与弊端
    17 ~ express ~ 分类的显示 ,修改 和 删除
    Express ~ 获取表单 get 和 post 提交方式传送参数的对比
    16 ~ express ~ 添加博客分类
    JS ~ Promise 对象
    JS ~ Promise.reject()
    JS ~ 返回上一步
    PHP ~ 通过程序删除图片,同时删除数据库中的图片数据 和 图片文件
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9216204.html
Copyright © 2011-2022 走看看