zoukankan      html  css  js  c++  java
  • LeetCode 328. Odd Even Linked List(链表元素按奇偶聚集)

    题意:给定一个链表,链表元素按奇偶聚集,奇数位置的结点在前面,偶数位置的结点在后面。

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

    分析:

    法一:递归。

    (1)先递归oddEvenList(head -> next -> next),链表此时为2->1->(递归结果:3->6->7->5->4)

    (2)把2插入到3(递归结果奇数位的第一个位置)前面,把1插入到5前面(递归结果偶数位的第一个位置)

    此法缺点,每次递归都要求当前链表长度,时间复杂度肯定超O(n)了,不推荐

    /**
     * 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 == NULL || head -> next == NULL || head -> next -> next == NULL) return head;
            ListNode *tmp = head;
            int len = 0;
            while(tmp){
                tmp = tmp -> next;
                ++len;
            }
            ListNode *suf1 = head -> next;
            ListNode *suf2 = oddEvenList(head -> next -> next);
            head -> next = suf2;
            if(len % 2 == 0){
                len = (len - 2) / 2 - 1;
            }
            else{
                len = (len - 2) / 2;
            }
            tmp = suf2;
            while(len--){
                tmp = tmp -> next;
            }
            suf1 -> next = tmp -> next;
            tmp -> next = suf1;
            return head;
        }
    };
    

    法二:奇数位连奇数位,偶数位连偶数位,然后奇数位链表末尾接偶数位链表开头。

    /**
     * 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 == NULL) return NULL;
            ListNode* odd = head;
            ListNode* even = head -> next;
            ListNode* evenhead = head -> next;
            while(even && even -> next){
                odd -> next = odd -> next -> next;
                odd = odd -> next;
                even -> next = even -> next -> next;
                even = even -> next;
            }
            odd -> next = evenhead;
            return head;
        }
    };
    

      

  • 相关阅读:
    DHCP配置实例
    upupw phpmyadmin写shell
    网络配置课学期总结
    c#写一个网站后台扫描器
    移位运算符
    JavaScript 事件
    JS自动爆炸案例
    生成树协议
    暴力操作节点
    为博客园添加统计访问量的工具
  • 原文地址:https://www.cnblogs.com/tyty-Somnuspoppy/p/12380065.html
Copyright © 2011-2022 走看看