zoukankan      html  css  js  c++  java
  • LeetCode() Reorder List

    超时,思路感觉很好,每次反转,

    /**
     * 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) {
            int index=1;
            ListNode* tem=head;
            while(tem)
            {
                if(index++ %2 == 1)
                {
                    tem->next=reverseList(tem->next);
                }
                else
                    tem=tem->next;
            }
        }
        ListNode* reverseList(ListNode* head) {
    		if (head == NULL)
    			return head;
    		ListNode* H = head;
    		head = head->next;
    		H->next = NULL;
    		while (head)
    		{
    			ListNode* next = head->next;
    			head->next = H;
    			H = head;
    			head = next;
    		}
    		return H;
    	}
    };
    

      还有一个思路是:从中间断开,找到后一半的链表,反转后一半链表,依次插入

    /**
     * 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 || head->next->next==NULL)
                return ;
            ListNode* slow=head,*fast=head;
            while(fast)
            {
                slow=slow->next;
                
                fast=fast->next->next;
                if(fast->next==NULL || fast->next->next==NULL)
                    break;
            }
            ListNode* second=(slow->next);
            slow->next=NULL;
            second=reverseList(second);
            ListNode* tem=head;
            while(second)
            {
                ListNode* sec_t=second->next;
                second->next=tem->next;;
                tem->next=second;
                tem=tem->next->next;
                second=sec_t;
            }
            
    	}
    	ListNode* reverseList(ListNode* head) {
    		if (head == NULL)
    			return head;
    		ListNode* H = head;
    		head = head->next;
    		H->next = NULL;
    		while (head)
    		{
    			ListNode* next = head->next;
    			head->next = H;
    			H = head;
    			head = next;
    		}
    		return H;
    	}
    };
    

      

  • 相关阅读:
    C++界面库(十几种,很全)
    前端框架
    Asp.Net Web Api 接口,拥抱支持跨域访问。
    WEB控件
    MVC之验证
    AJAX跨域调用ASP.NET MVC或者WebAPI服务
    VS生产的编辑方法和编辑窗体
    DDD(领域驱动设计)应对具体业务场景,Domain Model(领域模型)到底如何设计?
    Redis简介与简单安装
    Cocos2d-x 3.1.1开发环境
  • 原文地址:https://www.cnblogs.com/yanqi110/p/5002580.html
Copyright © 2011-2022 走看看