LeetCode 147
Insertion Sort List
Problem Description:
对链表按照结点值从小到大进行排序。
具体的题目信息:
https://leetcode.com/problems/insertion-sort-list/description/Solution:
解题思路
本题用两个指针指向进行比较的前后两个结点,如果后面结点值不小于前面结点值,则将两个指针分别右移一位。如果后面结点值小于前面结点值,需要从头开始遍历找到插入的位置。编程实现
/**
* 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 head;
if (head->next == NULL)
return head;
ListNode* t, *temp;
ListNode* p = head;
ListNode* q = head->next;
while(q) {
//若后面结点值不小于前面结点值,两指针同时移动
if (p->val <= q->val) {
p = p->next;
q = q->next;
} else {
//判断q指向结点值是否小于头结点,如果是,在进行插入后还需要头结点的位置
if (q->val <= head->val) {
t = q->next;
p->next = q->next;
q->next = head;
head = q;
q = t;
} else {
//若不是,从头开始遍历,通过与temp->next的值进行比较,确定插入位置的前一个结点
temp = head;
while(q->val > temp->next->val) {
temp = temp->next;
}
t = q->next;
p->next = q->next;
q->next = temp->next;
temp->next = q;
q = t;
}
}
}
return head;
}
};