• Reorder List


    Given a singly linked list LL0L1→…→Ln-1Ln,
    reorder it to: L0LnL1Ln-1L2Ln-2→…

    You must do this in-place without altering the nodes' values.

    For example,
    Given {1,2,3,4}, reorder it to {1,4,2,3}.

    注意细节, 先求中间结点, 再反转后半, 再结合一起

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode *middleNode(ListNode *root)
        {
           if(!root||!root->next)
            return root;
           ListNode *p,*q;
           p = root;
           q = root;
           while(p->next&&p->next->next)
           {
               p = p->next->next;
               q = q->next;
           }
            return q;
        }
        ListNode *reverseList(ListNode *root)
        {
            if(!root||!root->next)
                return root;
            ListNode *p,*q,*tem;
            p = root;
            q = NULL;
            while(p)
            {
                if(!q)
                {
                    p = p->next;
                    q = root;
                    q->next = NULL;
                    continue;
                }
              tem = p;
              p   = p->next;
              tem->next = q;
              q = tem;
            }
            return q;
        }
        void reorderList(ListNode *head) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            if(!head||!head->next)
                return;
            ListNode *middle_node = middleNode(head);
            ListNode *newHead     = reverseList(middle_node->next);
            middle_node->next = NULL;
            
            ListNode *p,*q,*r,*s;
            p = head;
            q = newHead;
            while(p&&q)
            {
                r = p->next;
                s = q->next;
                p->next = q;
                q->next = r;
                p = r;
                q = s;
                
            }
        }
    };


    每天早上叫醒你的不是闹钟,而是心中的梦~
  • 相关阅读:
    yum报错Python版本不兼容
    MySQL——checkpoint
    MySQL体系结构——内存
    MySQL体系结构——存储引擎
    ORA-00972: identifier is too long 问题处理
    day08面向对象、jsonpath操作、写日志
    day07mock edis加密
    数据库增删改查封装
    day06数据库、发送邮件、操作excel等
    pycharm的使用
  • 原文地址:https://www.cnblogs.com/vintion/p/4116963.html
Copyright © 2020-2023  润新知