/*
* 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;
//}
Insertion Sort List
最新推荐文章于 2022-04-09 13:42:00 发布