• 148. Sort List


    148. Sort List

    题目

    Sort a linked list in O(n log n) time using constant space complexity.
    

    解答Accept

    • 实现之前看了思路,想想先就用递归实现
    • 结果模仿别人写都有5个bug,感觉没有用心啊!!!
    // Definition for singly - linked list.
    struct ListNode {
    	int val;
    	ListNode *next;
    	ListNode(int x) : val(x), next(NULL) {}
    };
    
    // sort list
    class Solution {
    public:
    
    	ListNode* findMiddle(ListNode* head)
    	{
    		ListNode* slow = head;
    		ListNode* fast = head->next;
    		while (fast&&fast->next) //bug1 ||
    		{
    			slow = slow->next;
    			fast = fast->next->next;
    		}
    		return slow;
    	}
    
    	ListNode* MergeList(ListNode* left, ListNode*right)
    	{
    		if (left==NULL)
    		{
    			return right;
    		}
    		if (right==NULL)
    		{
    			return left;
    		}
    
    		ListNode* temp = new ListNode(0);
    		ListNode* temp_head = temp;  //bug2 头指针移动
    		while (left&&right)
    		{
    			if (left->val<right->val)
    			{
    				temp->next = left;  //bug3 顺序反了
    				left = left->next;
    				
    			}
    			else
    			{
    				temp->next = right;
    				right = right->next;
    			}
    			temp = temp->next;
    		}
    
    		if (left) //bug4 if->while
    		{
    			temp->next = left;
    		}
    		if (right)
    		{
    			temp->next = right;
    		}
    
    		return temp_head->next;
    
    	}
    	ListNode* sortList(ListNode* head) {
    
    		if (!head||!head->next)  // Line 57: member access within null pointer of type 'struct ListNode'
    		{
    			return head;  //bug5 忘记取!
    		}
    		
    		ListNode *middle = findMiddle(head);
    
    
    		ListNode* left=sortList(middle->next);
    
    		middle->next = NULL;
    		ListNode* right = sortList(head);
    
    		ListNode *ret=MergeList(left, right);
    		return  ret;
    	}
    };
    
    

    题目来源:148. Sort List,讨论里面非递归实现

  • 相关阅读:
    Mybatis(4) 映射文件-参数处理
    Mybatis(3) 映射文件-增删改查
    Mabatis(2) 全局配置文件
    Mybatis(1) 创建Mybatis HelloWorld
    过滤器和拦截器之间的区别
    Redis(3) 配置文件 redis.conf
    Redis(2) 数据类型
    Redis(1) 初识Redis
    ActiveMQ(4) ActiveMQ JDBC 持久化 Mysql 数据库
    8.字典
  • 原文地址:https://www.cnblogs.com/ranjiewen/p/8075675.html
Copyright © 2020-2023  润新知