码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode() Reorder List

时间:2015-11-28 14:52:54      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

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

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

  

LeetCode() Reorder List

标签:

原文地址:http://www.cnblogs.com/yanqi110/p/5002580.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!