zoukankan      html  css  js  c++  java
  • 99. 重排链表

    99. 重排链表 

     
     
    难度系数 中等 通过率 24%

    给定一个单链表L: L0→L1→…→Ln-1→Ln,

    重新排列后为:L0→Ln→L1→Ln-1→L2→Ln-2→…

    必须在不改变节点值的情况下进行原地操作。

    样例

    给出链表 1->2->3->4->null,重新排列后为1->4->2->3->null

    /**
     * Definition of ListNode
     * class ListNode {
     * public:
     *     int val;
     *     ListNode *next;
     *     ListNode(int val) {
     *         this->val = val;
     *         this->next = NULL;
     *     }
     * }
     */
    
    
    class Solution {
    public:
        /*
         * @param head: The head of linked list.
         * @return: nothing
         */
        void reorderList(ListNode * head) {
            // write your code here
            	if (head == nullptr || head->next == nullptr)
            	{
            		return;
            	}
            
            	ListNode *slow = head, *fast = head->next;
            
            	while(fast&&fast->next)
            	{
            		slow = slow->next;
            		fast = fast->next->next;
            	}
            
            	fast = slow->next;
            	slow->next = nullptr;
            	ListNode *rHead = nullptr;
            	while (fast)
            	{
            		ListNode *r = fast->next;
            		fast->next = rHead;
            		rHead = fast;
            		fast = r;
            	}
            
            
            	fast = rHead;
            	slow = head;
            	while(slow&&fast)
            	{
            		ListNode *rr = fast->next;
            		ListNode *lr = slow->next;
            		fast->next = lr;
            		slow->next = fast;
            
            		fast = rr;
            		slow = lr;
            	}
        }
    };
    

      

  • 相关阅读:
    [CC-STREETTA]The Street
    [CF115E]Linear Kingdom Races
    [洛谷P3987]我永远喜欢珂朵莉~
    [POI2012]Squarks
    [TC6194]AllWoundUp
    [CF434D]Nanami's Power Plant
    [CF126D]Fibonacci Sums/[BJOI2012]最多的方案
    [HZOI 2016]我们爱数数
    [COGS2427][HZOI 2016]seq
    Ynoi2018 天降之物
  • 原文地址:https://www.cnblogs.com/kanekiken/p/8047946.html
Copyright © 2011-2022 走看看