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

      

  • 相关阅读:
    OCP-052考试题库汇总(35)-CUUG内部解答版
    OCP-052考试题库汇总(34)-CUUG内部解答版
    018 ThreadLocal实现线程安全
    017 无锁与CAS
    016 原子类
    015 可见性问题与volatile
    014 锁重入
    013 synchronized的优化
    012 内置锁和synchronized
    011 线程安全性问题
  • 原文地址:https://www.cnblogs.com/yanqi110/p/5002580.html
Copyright © 2011-2022 走看看