首页 > 其他 > 详细

leetcode Insertion Sort List

时间:2014-03-23 23:50:56      阅读:722      评论:0      收藏:0      [点我收藏+]

表示我觉得题目给的接口有点问题,还是我自己理解有问题。如果链表没有头节点,那么必须是传指针的引用啊!

下面贴代码:

#include <string>
#include <vector>
#include <stack>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "ListNode.cpp"

using namespace std;

class Solution {
public:
    ListNode *insertionSortList(ListNode*& head) {
        if (!head || !head->next){
        	return head;
        }
        
        ListNode* begin = head;
        ListNode* pre = begin;
        ListNode* cur = pre->next;
        
        begin->next = NULL;
        
        ListNode* tmp = begin;
    	
    	while (cur){
    		pre = begin;
    		tmp = begin;
	    	while (tmp){
	    		if (tmp->val > cur->val){
	    			break;
	    		}
	    		
	    		pre = tmp;
	    		tmp = tmp->next;
	    	}
	    	
		    ListNode* toInsert = cur;
			cur = cur->next;
			
	    	if (!tmp){
	    		pre->next = toInsert;
	    		pre->next->next = NULL;
	    	}
			else{
				if (pre == tmp){
					toInsert->next = tmp;
					begin = toInsert;
	    		}
	    		else{
	    			pre->next = toInsert;
					toInsert->next = tmp;	
	    		}
			}
    	}
    	
    	head = begin;
    }
};

int main(){
	ListNode* head = NULL;
	insert(head, 2);
	insert(head, 1);
	//insert(head, -1);
	Solution s;
	s.insertionSortList(head);
	print(head);
}

表示思路很简单,就是利用插入排序的思想,前面的链表都是排好序的,下一个未排序的节点从头到它的前一个节点扫描,直到找到比他大的点,此时插入。

但需要注意的是链表节点的截断,不过都比较基础,相信稍微想想大家都做得出来!

leetcode Insertion Sort List,布布扣,bubuko.com

leetcode Insertion Sort List

原文:http://blog.csdn.net/boyxiaolong/article/details/21885331

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!