zoukankan      html  css  js  c++  java
  • [LeetCode]97. Reorder List链表重排序

    Given a singly linked list L: L0L1→…→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}.

    Subscribe to see which companies asked this question

     
    解法:仔细分析题目意思,一个简单的方法就是将后半部分链表先逆转,然后插入到前半部分。因此可以写出如下代码:
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        void reorderList(ListNode* head) {
            if(head == NULL || head->next == NULL) return;
            ListNode *slow = head, *fast = head;
            while(fast->next != NULL && fast->next->next != NULL) {
                slow = slow->next;
                fast = fast->next->next;
            }        
            ListNode* head1 = head;
            ListNode* head2 = slow->next;
            head2 = reverseList(head2);
            slow->next = NULL;
            while(head2 != NULL) {
                ListNode *next1 = head1->next, *next2 = head2->next;
                head1->next = head2;
                head2->next = next1;
                head1 = next1;
                head2 = next2;
            }
        }
    private:
        ListNode* reverseList(ListNode* head) {
            ListNode* rHead = NULL;
            ListNode* curr = head;
            ListNode* pTail = NULL;
            while(curr != NULL) {
                ListNode* pNext = curr->next;
                if(pNext == NULL)
                    rHead = curr;
                curr->next = pTail;
                pTail = curr;
                curr = pNext;
            }
            return rHead;
        }
    };
  • 相关阅读:
    IDEA控制台输出中文乱码问题
    JAVA web 框架集合
    去掉VSS控制
    .Net Core .Net Core V1.0 创建MVC项目
    .Net Core .Net Core的学习
    WebService 天气预报webservice接口
    SMS106 短信验证码接口测试
    Regex 常用的正则表达式
    Jquery Plugins Jquery Validate
    MVC 路由调试工具-RouteDebugger
  • 原文地址:https://www.cnblogs.com/aprilcheny/p/5018498.html
Copyright © 2011-2022 走看看