LeetCode Insertion Sort List
2014-07-15 10:20
429 查看
Sort a linked list using insertion sort.
/**
* 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) {
ListNode *pNode = head;
if (head == NULL || head->next == NULL)
return head;
while (pNode->next != NULL) {
ListNode *ptemp = pNode->next;
pNode->next = ptemp->next;
ListNode *ps = head;
ListNode *pbehind = head;
while (ps != pNode->next) {
if (ps->val < ptemp->val) {
pbehind = ps;
ps = ps->next;
} else
break;
}
if (ps == head) {
ptemp->next = ps;;
head = ptemp;
}
else if (pbehind == pNode) {
ptemp->next = ps;
pbehind->next = ptemp;
pNode = pNode->next;
}
else {
ptemp->next = ps;
pbehind->next = ptemp;
}
}
return head;
}
};
/**
* 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) {
ListNode *pNode = head;
if (head == NULL || head->next == NULL)
return head;
while (pNode->next != NULL) {
ListNode *ptemp = pNode->next;
pNode->next = ptemp->next;
ListNode *ps = head;
ListNode *pbehind = head;
while (ps != pNode->next) {
if (ps->val < ptemp->val) {
pbehind = ps;
ps = ps->next;
} else
break;
}
if (ps == head) {
ptemp->next = ps;;
head = ptemp;
}
else if (pbehind == pNode) {
ptemp->next = ps;
pbehind->next = ptemp;
pNode = pNode->next;
}
else {
ptemp->next = ps;
pbehind->next = ptemp;
}
}
return head;
}
};
相关文章推荐
- LeetCode_Insertion Sort List
- leetcode. Insertion Sort List
- leetcode_Sort a linked list using insertion sort.
- leetcode_147题——Insertion Sort List(线性表,插入排序)
- 【leetcode】Insertion Sort List
- Java for LeetCode 147 Insertion Sort List
- Insertion Sort List Leetcode java
- LeetCode: Insertion Sort List(外加对单链表类题目的思考总结)
- LeetCode | Insertion Sort List
- [Leetcode]Insertion Sort List
- leetcode insertionSortList
- [Leetcode] #147 Insertion Sort List
- Leetcode: insertion-sort-list
- 【LeetCode with Python】 Insertion Sort List
- LeetCode:Insertion Sort List (Java)
- LeetCode: Insertion Sort List
- LeetCode—Insertion Sort List
- [LeetCode]Insertion Sort List
- leetcode 链表 Insertion Sort List
- LeetCode – Refresh – Insertion Sort List