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;
            	}
        }
    };
    

      

  • 相关阅读:
    Excel教程(5)
    Excel教程(4)
    Excel教程(3)
    Excel教程(2)
    如何在Excel中少犯二(I)
    for zip
    temp
    study
    eclipse
    shell
  • 原文地址:https://www.cnblogs.com/kanekiken/p/8047946.html
Copyright © 2011-2022 走看看