Insertion Sort List

/*
 * Solution.cpp
 *
 *  Created on: 2014年4月8日
 *      Author: William
 */

#include <iostream>
using namespace std;
// Definition for singly-linked list.
struct ListNode {
	int val;
	ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};

class Solution {
public:
	ListNode *insertionSortList(ListNode *head) {
		if (head == NULL)
			return NULL;
		ListNode *newhead = head;
		head = head->next;
		newhead->next = NULL;
		while (head != NULL) {
			if (head->val < newhead->val) {
				ListNode *tmp = head->next;
				head->next = newhead;
				newhead = head;
				head = tmp;
				continue;// Use continue to avoid else, making structure of the code simpler.
			}
			ListNode *pre = newhead, *p = pre->next;
			while (p != NULL && p->val < head->val) {
				p = p->next;
				pre = pre->next;
			}
			// The pretty part here is that no matter which condition makes the loop stop,
			// the following operations are the same. (insert | append)
			pre->next = head;
			head = head->next;
			pre->next->next = p;
		}
		return newhead;
	}

	void printList(ListNode *head) {
		ListNode *p = head;
		while (p != NULL) {
			cout << p->val << " ";
			p = p->next;
		}
		cout << endl;
	}
};

//int main() {
//	Solution pro;
//	ListNode l1 = ListNode(5);
//	ListNode l2 = ListNode(2);
//	ListNode l3 = ListNode(1);
//	ListNode l4 = ListNode(4);
//	l1.next = &l2;
//	l2.next = &l3;
//	l3.next = &l4;
//	pro.printList(&l1);
//	ListNode *nh = pro.insertionSortList(&l1);
//	pro.printList(nh);
//	return 0;
//}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值