zoukankan      html  css  js  c++  java
  • Leetcode: Reorder List

    FROM 

    思路

    1. 将后半段截取下来再倒序, 插入到前半段, 时间复杂度为 o(n)

    代码

    #include <iostream>
    using namespace std;
    
    struct ListNode {
         int val;
         ListNode *next;
         ListNode(int x) : val(x), next(NULL) {}
     };
    
    class Solution {
    public:
        void reorderList(ListNode *head) {
          if(head == NULL)
            return;
          
      		int size = 0;
      		ListNode *curNode = head;
      		while(curNode) {
      			size++;
      			curNode = curNode->next;
      		}	
    
      		int step = size - (size >> 1); // pick the larger part
      		ListNode *cursor1 = head, *cursor2 = head;
      		
          while(--step)
      			cursor2 = cursor2->next;
          ListNode *tmp = cursor2;
          
          if(tmp != NULL) {
            cursor2 = tmp->next;
            tmp->next = NULL;
          }
    
      		cursor2 = reverseList(cursor2);
      		while(cursor2) {
      			ListNode *tmp = cursor2;
      			cursor2 = cursor2->next;
      			tmp->next = cursor1->next;
      			cursor1->next = tmp;
      			cursor1 = tmp->next;
      		}
        }
    
        ListNode* reverseList(ListNode* head) {
        	if(head == NULL)
        		return head;
    
        	ListNode *curNode = head;
        	while(curNode->next) {
        		ListNode *nextNode = curNode->next;
        		curNode->next = nextNode->next;
        		nextNode->next = head;
        		head = nextNode;
        	}
        	return head;
        }
    };
    
    int main() {
    	int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8};
    	ListNode* list[10];
    	int len = 3;
    	for(int i = 0; i < len; i ++) 
    		list[i] = new ListNode(arr[i]);
    	for(int i = 0; i < len-1; i ++)
    		list[i]->next = list[i+1];
    	(new Solution())->reorderList(list[0]);
    	ListNode *lists = list[0];
    	while(lists) {
    		cout << lists->val << " ";
    		lists = lists->next;
    	}
    	cout << endl;
    	return 0;
    }
    

      

  • 相关阅读:
    设计模式中的多态——策略模式详解
    Spring IOC容器启动流程源码解析(一)——容器概念详解及源码初探
    并发包下常见的同步工具类详解(CountDownLatch,CyclicBarrier,Semaphore)
    HNOI2020游记
    旧年之末,新年伊始
    退役V次后做题记录
    PKUWC2020 游记
    CSP2019退役记
    CTS/APIO2019游记
    HNOI2019游记
  • 原文地址:https://www.cnblogs.com/xinsheng/p/3550121.html
Copyright © 2011-2022 走看看